Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 4: User-Defined Types & Memory Management
C ⏱ 14 min read

Dynamic Memory Allocation (malloc, calloc, realloc, free)

Static arrays must have their size known at compile time. Dynamic memory allocation lets you request memory from the OS at runtime based on real-time user needs.

What is it?

Dynamic memory allocation allocates memory on the Heap at runtime using `<stdlib.h>` functions: `malloc()`, `calloc()`, `realloc()`, and `free()`.

Why is it used?

Essential for resizable arrays, linked lists, trees, and handling datasets of unpredictable sizes without wasting RAM.

Detailed Explanation

Heap Memory Management Functions: • `malloc(size)`: Allocates `size` bytes of uninitialized memory. Returns `void*` pointer (or `NULL` if out of memory). • `calloc(n, size)`: Allocates and clears memory, initializing every byte to zero. • `realloc(ptr, new_size)`: Resizes an existing memory block, preserving previous contents. • `free(ptr)`: Releases allocated memory back to the operating system. Memory Leaks: If you allocate memory with `malloc()` or `calloc()` and lose the pointer without calling `free()`, that memory remains leaked and unusable until the process terminates!

Syntax Structure

Syntax Blueprint
int *arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) { /* Out of memory */ }
free(arr);
arr = NULL; // Prevent dangling pointer

Code Example

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

int main() {
    int num_students = 3;
    
    // 1. Allocate heap memory for 3 integer roll numbers
    int *roster = (int*)malloc(num_students * sizeof(int));
    if (roster == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
    
    // Populate initial roster
    roster[0] = 101; roster[1] = 102; roster[2] = 103;
    printf("Initial 3 students allocated on Heap.\n");
    
    // 2. Expand roster to 5 students using realloc
    num_students = 5;
    int *temp = (int*)realloc(roster, num_students * sizeof(int));
    if (temp == NULL) {
        free(roster);
        return 1;
    }
    roster = temp;
    roster[3] = 104;
    roster[4] = 105;
    
    printf("Expanded Roster on Heap: ");
    for (int i = 0; i < num_students; i++) {
        printf("%d ", roster[i]);
    }
    printf("\n");
    
    // 3. Free memory to prevent memory leaks!
    free(roster);
    roster = NULL; // Safe practice
    printf("Memory successfully freed back to operating system.\n");
    
    return 0;
}

Explanation of the Code

• `malloc(n * sizeof(int))` allocates space dynamically on the heap. • Always checks `if (roster == NULL)` to guard against memory exhaustion. • `realloc` smoothly resizes the heap block. • `free(roster)` deallocates memory, and `roster = NULL` prevents dangling pointers.

Expected Output

Initial 3 students allocated on Heap. Expanded Roster on Heap: 101 102 103 104 105 Memory successfully freed back to operating system.

Real-World Application

Used in Redis in-memory cache, browser tab memory allocators, and operating system kernels.

Common Mistakes to Avoid

• Forgetting to call `free()` causing memory leaks. • Using memory after calling `free()` (use-after-free vulnerability). • Double free (calling `free(ptr)` twice on the same pointer).

Quick Practice Challenge

Allocate memory for an array of 4 floats using `calloc`, verify all values are initialized to 0.0, then free it.

Key Takeaways

• `malloc()` allocates uninitialized memory; `calloc()` zero-initializes. • Always check if the returned pointer is `NULL`. • Always call `free()` when done to prevent memory leaks.