C - Dynamic Memory Management in C

Dynamic Memory Management refers to allocating and deallocating memory at run time as per program requirements, instead of fixing memory size at compile time.

In C, dynamic memory is managed using library functions provided in the header file <stdlib.h>.


Need for Dynamic Memory Allocation

  • When memory size is not known in advance

  • Efficient utilization of memory

  • To create dynamic data structures like linked lists, stacks, queues, trees

  • Avoids memory wastage compared to static allocation


Memory Areas Used

Dynamic memory is allocated from the heap memory, while static and automatic variables use stack or data segment.


Dynamic Memory Allocation Functions in C

1. malloc() (Memory Allocation)

  • Allocates a single block of memory

  • Memory contents are uninitialized

  • Returns a pointer of type void*

Syntax:

ptr = (datatype*)malloc(size_in_bytes);

Example:

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

2. calloc() (Contiguous Allocation)

  • Allocates multiple blocks of memory

  • Memory is initialized to zero

  • Returns a pointer to allocated memory

Syntax:

ptr = (datatype*)calloc(n, size);

Example:

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

3. realloc() (Reallocation)

  • Changes the size of previously allocated memory

  • Preserves existing data (up to the smaller size)

Syntax:

ptr = realloc(ptr, new_size);

Example:

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

4. free() (Deallocation)

  • Releases dynamically allocated memory

  • Prevents memory leaks

Syntax:

free(ptr);

Example:

free(p);

Example Program

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

int main() {
    int n, *arr;
    scanf("%d", &n);

    arr = (int*)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory not allocated");
        return 0;
    }

    free(arr);
    return 0;
}

Advantages

  • Memory allocated only when required

  • Better memory utilization

  • Supports complex data structures


Disadvantages

  • Memory leaks if free() is not used

  • Dangling pointers

  • Slightly slower than static allocation

  • Programmer must manage memory manually


Comparison: Static vs Dynamic Memory Allocation

Static Allocation Dynamic Allocation
Compile-time Run-time
Fixed size Flexible size
Stack/Static area Heap memory
Faster Slightly slower