Dynamically Allocated Memory
Learn how to control the amount of memory allocated for a variable on a heap by using some built in C functions.
Languages like MATLAB, Python, etc, allow us to work with data structures like arrays, lists, etc, that we can dynamically resize. That is to say, we can make them longer, shorter, etc, even after they are created. In C, this is not so easy.
Once we’ve allocated a variable such as an array on the stack, it is fixed in its size. We cannot make it longer or shorter. In contrast, if we use the functions malloc
or calloc
to allocate an array on the heap, we can use the function realloc
to resize it at some later time. In order to use these functions we need to include stdlib.h
at the top of our C file.
The built-in functions malloc
, calloc
, realloc
memcpy
and free
are what we use to manage dynamically allocated data structures on the heap, “by hand”. The life cycle of a heap variable involves three stages:
- Allocating heap memory for the variable using
malloc
orcalloc
- (Optionally) resizing the allocated memory using
realloc
- Releasing the memory from the heap using
free
Allocating memory using malloc
or calloc
These functions are used to allocate memory at runtime. The malloc
function takes as input the size of the memory block to be allocated. The calloc
function is like malloc
except that it also initializes all elements to zero. The calloc
function takes two input arguments, the number of elements and the size of each element.
Here’s an example of using malloc
to allocate memory to hold an array of 10 structs:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy