Dynamic Memory Allocation Functions
Learn the basic functions for dynamic memory allocation.
Introduction
We want to figure out how to allocate memory on the heap. Unlike stack allocations, we have to use specialized functions to allocate memory on the stack.
These functions are as follows:
malloc
calloc
free
We must include the stdlib.h
header file to use dynamic allocation functions.
The malloc
function
The malloc
function is the most common memory allocation function.
Prototype:
void *malloc(size_t size);
- It allocates a block of
size
bytes. - It returns a pointer to the beginning of the allocated memory block or
NULL
if the allocation fails (not enough space, for example). - In the prototype, the return type is a
void
pointer. Let’s ignore this aspect for now. Just assume that it returns the data type that we need. We’ll explore genericity usingvoid
pointers in the upcoming lessons
The malloc
function doesn’t care about data types. It allocates some bytes, and that’s it. The memory is just a sequence of bytes and knows nothing of data types. The difference comes from how we interpret the memory returned by malloc
.
If we want to allocate an int
, we must pass its size. We tell malloc
to allocate enough space to hold 4 bytes, which is enough for an int
.
malloc(sizeof(int));
To interpret this memory as the address of an integer, use an int*
pointer.
int* var = malloc(sizeof(int));
After we allocate the memory, we can use it like any other pointer. However, we must verify that it isn’t NULL
before working with it.
See the code below, where we allocate an integer, write 5
to it and print the value.
Get hands-on with 1400+ tech skills courses.