C

Dynamic Memory Allocation in C Programming

In C, memory can be allocated in two ways: Static and Dynamic. Static memory allocation (like int arr[10];) occurs at compile time, and the size must be fixed. Dynamic Memory Allocation (DMA), however, allows a program to request exactly the amount of memory it needs during execution (runtime).

This is essential for building scalable applications where the amount of data is unknown beforehand, such as a list of students that grows as more people register.

1. The Theory: Stack vs. Heap

To understand DMA, you must understand the two primary areas of memory used by a program:

  • The Stack: This is where local variables and function parameters are stored. It is managed automatically by the compiler. When a function ends, its stack memory is reclaimed. The stack is fast but limited in size.

  • The Heap: This is a large pool of "free" memory available to the program. DMA happens on the Heap. Unlike the stack, memory on the heap is not managed by the compiler; the programmer is responsible for allocating it and—more importantly—releasing it.

2. The Standard Library Functions

DMA is performed using four functions defined in the <stdlib.h> header file.

A. malloc() (Memory Allocation)

  • Theory: It reserves a single contiguous block of memory of a specified number of bytes.

  • Initialization: It does not clear the memory; it contains "garbage values."

  • Return Value: It returns a void* (generic pointer), which must be type-casted to the desired type. If allocation fails, it returns NULL.

  • Syntax: ptr = (cast_type*) malloc(byte_size);

B. calloc() (Contiguous Allocation)

  • Theory: Similar to malloc, but used specifically for arrays. It takes two arguments: the number of elements and the size of each element.

  • Initialization: It automatically initializes all bytes to zero.

  • Syntax: ptr = (cast_type*) calloc(n, element_size);

C. realloc() (Re-allocation)

  • Theory: It changes the size of previously allocated memory without losing the old data. If the current block cannot be expanded, it finds a new, larger block, copies the data, and frees the old block.

  • Syntax: ptr = realloc(ptr, new_size);

D. free() (De-allocation)

  • Theory: This is the most critical function. It releases the memory back to the heap so other programs or parts of your program can use it.

  • Syntax: free(ptr);

3. Practical Code Example

This program demonstrates allocating an array whose size is determined by the user at runtime.


#include <stdio.h>
#include <stdlib.h> // Required for DMA functions

int main() {
    int n, *arr;

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

    // 1. Allocate memory using malloc
    arr = (int*) malloc(n * sizeof(int));

    // 2. Check if memory allocation was successful
    if (arr == NULL) {
        printf("Memory not allocated. System out of memory.\n");
        return 1; // Exit program
    }

    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]); // Can use array notation with pointers
    }

    printf("The elements are: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", *(arr + i));
    }

    // 3. Free the allocated memory
    free(arr);
    printf("\nMemory successfully freed.\n");

    return 0;
}

4. Critical Theory: Common Dangers

A. Memory Leaks

A memory leak occurs when a programmer allocates memory on the heap but forgets to free() it. If this happens in a loop or a long-running server, the program will eventually consume all available RAM, causing the system to slow down or crash.

B. Dangling Pointers

If you free(ptr) but then try to access *ptr later, you are accessing a dangling pointer. The memory no longer belongs to your pointer.

  • Best Practice: After calling free(ptr);, immediately set ptr = NULL;.

C. Fragmentation

Frequent allocation and de-allocation of small blocks can lead to "External Fragmentation," where there is enough total free memory, but it is split into tiny, non-contiguous pieces that cannot satisfy a large malloc request.

5. Summary Table

FunctionPurposeInitial ValueArguments
malloc()Allocates a single block.GarbageTotal bytes.
calloc()Allocates multiple blocks.ZeroNum elements, size per element.
realloc()Resizes existing block.Preserves old dataOld pointer, new size.
free()Releases memory.N/APointer to be freed.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now