ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C Programming Tutorial• 8 min read

Dynamic Memory Allocation: malloc, calloc, realloc & free

Heap memory allocation, memory leaks, and dangling pointer prevention

Dynamic memory enables programs to request arbitrary bytes from the operating system Heap at runtime via <stdlib.h>. Every allocated byte must be manually freed.

The Heap Allocation Lifecycle

malloc(size_in_bytes): Allocates uninitialized memory on the heap. Always check if the returned pointer is NULL (out of memory)!

calloc(num_elements, size): Allocates memory and initializes all bytes to zero.

realloc(ptr, new_size): Resizes an existing heap allocation.

free(ptr): Releases allocated memory back to the OS. Failing to call free causes a Memory Leak.

Best Practice: Immediately after free(ptr), assign ptr = NULL; to prevent Dangling Pointer bugs.

Dynamic Array Allocation with malloc and free
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 5;
    // Allocate array of 5 integers on Heap
    int *arr = (int*)malloc(n * sizeof(int));
    if (arr == NULL) {
        fprintf(stderr, "Out of memory error!\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    // Free allocated memory to prevent memory leak!
    free(arr);
    arr = NULL; // Defend against dangling pointer

    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What occurs if a C program continuously allocates heap memory with `malloc()` but never calls `free()`?