C Dynamic Memory Allocation

In this article, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(), calloc(), free() and realloc()

An array is a collection of fixed number of values of a single type. That is, you need to declare the size of an array before you can use it.

Sometimes, the size of array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation in C programming.

There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C programming. They are malloc(), calloc(), realloc() and free().


C malloc()

The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form.


Syntax of malloc()

ptr = (cast-type*) malloc(byte-size)

Example:

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

Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

However, if the space is insufficient, allocation fails and returns a NULL pointer.


C calloc()

The name "calloc" stands for contiguous allocation.

The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of memory and initializes them to zero.


Syntax of calloc()

ptr = (cast-type*)calloc(n, element-size);

Example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of float.


C free()

Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must explicitly use free() to release the space.


Syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by ptr.


Example 1: malloc() and free()

This program calculates the sum of n numbers entered by the user. To perform this task, memory is dynamically allocated using malloc(), and memory is freed using free() function.

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

int main()
{
    int n, i, *ptr, sum = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));
    if(ptr == NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    printf("Enter elements: ");
    for(i = 0; i < n; ++i)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}

Example 2: calloc() and free()

This program calculates the sum of n numbers entered by the user. To perform this task, calloc() and free() is used.

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

int main()
{
    int n, i, *ptr, sum = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) calloc(n, sizeof(int));
    if(ptr == NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    printf("Enter elements: ");
    for(i = 0; i < n; ++i)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}

C realloc()

If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using realloc() function


Syntax of realloc()

ptr = realloc(ptr, x);

Here, ptr is reallocated with new size x.


Example 3: realloc()

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

int main()
{
    int *ptr, i , n1, n2;
    printf("Enter size of array: ");
    scanf("%d", &n1);

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

    printf("Addresses of previously allocated memory: ");
    for(i = 0; i < n1; ++i)
         printf("%u\n",ptr + i);

    printf("\nEnter new size of array: ");
    scanf("%d", &n2);
    ptr = realloc(ptr, n2 * sizeof(int));

    printf("Addresses of newly allocated memory: ");
    for(i = 0; i < n2; ++i)
         printf("%u\n", ptr + i);
    return 0;
}

When you run the program, the output will be:

Enter size of array: 2
Addresses of previously allocated memory:26855472
26855476

Enter new size of array: 4
Addresses of newly allocated memory:26855472
26855476
26855480
26855484