Skip to content

Allocating Memory

In C/C++ you can use the malloc function to ask to be allocated space in memory. You pass it the size of the space you are after, and it returns a pointer to the space you can use on the heap. The following image shows the overall idea of what we are aiming to achieve.

Conceptual view of what we are aiming to do

The following image shows the code needed to allocate space on the heap.

Malloc call with code highlighted

Example Code

The following example code uses malloc to create space for an integer, assigns it a value, and then free the allocation.

#include <stdlib.h>
#include "splashkit.h"
using std::to_string;
int main()
{
// Allocate memory for an integer on the heap
int *ptr = (int *)malloc(sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL)
{
write_line("Memory allocation failed");
return 1;
}
// Assign a value to the allocated memory
*ptr = 42;
// Print the value
write_line("Value: " + to_string(*ptr));
// Free the allocated memory
free(ptr);
ptr = NULL;
return 0;
}