Chapter 23 of 37

Dynamic Memory Allocation in C

Normally, when we create an array, we decide its size beforehand:

int numbers[5];

But what if we don't know how much memory we need until the program is running?

That's where Dynamic Memory Allocation comes in.

What is Dynamic Memory Allocation?

Dynamic memory allocation is the process of allocating memory during program execution instead of deciding its size beforehand.

C provides functions for this through the <stdlib.h> header.

The main functions are:

Function

Purpose

malloc()

Allocates memory

calloc()

Allocates and initializes memory

realloc()

Changes the size of allocated memory

free()

Releases allocated memory


malloc()

malloc() allocates a specified number of bytes of memory.

For example:

int *ptr = malloc(5 * sizeof(int));

This allocates enough memory for 5 integers.

Because malloc() returns a pointer to the allocated memory, we store it in ptr.


calloc()

calloc() also allocates memory, but it additionally initializes the allocated bytes to zero.

int *ptr = calloc(5, sizeof(int));

This allocates memory for 5 integers and initializes it to zero.


realloc()

Sometimes we need to increase or decrease the amount of allocated memory.

That's what realloc() is used for.

ptr = realloc(ptr, 10 * sizeof(int));

Now the allocated block is resized to hold enough space for 10 integers.

When using realloc(), it's important to handle possible allocation failure safely rather than overwriting the only pointer to the original block.


free()

Memory allocated dynamically should be released when it is no longer needed.

free(ptr);

This returns the allocated memory to the system.

If dynamically allocated memory is not properly released, the program can suffer from a memory leak.


Simple Example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *ptr = malloc(3 * sizeof(int));

    if (ptr == NULL)
    {
        return 1;
    }

    ptr[0] = 10;
    ptr[1] = 20;
    ptr[2] = 30;

    printf("%d %d %d", ptr[0], ptr[1], ptr[2]);

    free(ptr);

    return 0;
}

Output:

10 20 30

Here:

  1. malloc() allocates memory.

  2. ptr stores its address.

  3. We use the allocated memory like an array.

  4. free() releases the memory.

Static vs Dynamic Memory Allocation

Static/Automatic Allocation

Dynamic Allocation

Size is generally determined before or during block setup

Size can be decided at runtime

Example: int arr[5];

Example: malloc()

Automatically managed for local variables

Programmer must manage the allocated memory

Less flexible

More flexible

In Simple Words

Dynamic memory allocation allows a C program to request and manage memory while the program is running.

The four functions to remember are:

malloc()  → Allocate
calloc()  → Allocate + initialize to zero
realloc() → Resize
free()    → Release

Dynamic memory is especially important when working with linked lists, trees, dynamic arrays, and other data structures.