Dynamically Allocated Memory

In the heap, we can control the amount of memory allocated to a certain variable by using some built in C functions which we will discuss below.

Languages like MATLAB, Python, etc, allow you to work with data structures like arrays, lists, etc, that you can dynamically resize. That is to say, you can make them longer, shorter, etc, even after they are created. In C this is not so easy.

Once you have allocated a variable such as an array on the stack, it is fixed in its size. You cannot make it longer or shorter. In contrast, if you use malloc() or calloc() to allocate an array on the heap, you can use realloc() to resize it at some later time. In order to use these functions you will need to #include <stdlib.h> at the top of your C file.

The built-in functions malloc(), calloc(), realloc() memcpy() and free() are what you will use to manage dynamically allocated data structures on the heap, “by hand”. The life cycle of a heap variable involves three stages:

  1. allocating the heap variable using malloc() or calloc()
  2. (optionally) resizing the heap variable using realloc()
  3. 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