Memory Allocation in C

Dynamic Memory Allocation (DMA) in C is the process of allocating, reallocating, and freeing computer memory at runtime (during program execution) from the Heap segment. Unlike static or automatic memory allocation where array sizes must be fixed at compile-time, DMA enables programmers to request exactly the required amount of RAM on demand and release it as soon as it is no longer needed.

Memory Architecture of a C Program

When a C program runs, its memory space in RAM is organized into four distinct logical segments:

 1. Code / Text Segment: Contains compiled machine instructions (read-only).

 2. Data Segment (Initialized & BSS): Stores global and static variables.

 3. Stack Segment: Automatically stores local variables, function parameters, and return addresses (grows downwards).

 4. Heap Segment: A flexible pool of free memory managed explicitly by the programmer via DMA functions (grows upwards towards the stack).

The 4 Core Functions of Dynamic Memory Allocation

All dynamic memory functions are declared in the standard <stdlib.h> header file:

Function

Syntax Declaration

Description & Initialization

malloc()

void* malloc(size_t size);

Allocates a single continuous block of size bytes. Leaves memory uninitialized (contains garbage values).

calloc()

void* calloc(size_t n, size_t size);

Allocates memory for an array of n elements of size bytes each. Automatically initializes all bytes to zero.

realloc()

void* realloc(void *ptr, size_t new_size);

Resizes previously allocated memory block pointed to by ptr to new_size bytes while preserving existing data.

free()

void free(void *ptr);

Deallocates previously allocated heap memory and returns it back to the operating system pool.

Detailed Code Example: malloc vs calloc and realloc


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

int main()
{
    int *arr, n = 3, i;

    /* 1. Allocate using calloc (zero-initialized) */
    arr = (int*) calloc(n, sizeof(int));
    if(arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    printf("Initial elements (calloc auto-zeros):\n");
    for(i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    /* Assign values */
    for(i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    /* 2. Expand array to 5 elements using realloc */
    arr = (int*) realloc(arr, 5 * sizeof(int));
    if(arr == NULL) {
        printf("Reallocation failed!\n");
        return 1;
    }

    arr[3] = 40;
    arr[4] = 50;

    printf("\nAfter realloc to 5 elements:\n");
    for(i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    /* 3. Free heap memory */
    free(arr);
    arr = NULL; /* Prevent dangling pointer */

    return 0;
}
							

4 Fatal Dynamic Memory Pitfalls in C

 1. Memory Leak: Forgetting to call free() before losing the pointer address. Memory remains reserved and inaccessible until the program terminates.

 2. Dangling Pointer: Accessing memory through a pointer after calling free(ptr). Always assign ptr = NULL; after freeing.

 3. Double Free: Calling free(ptr) twice on the same memory block crashes the program with runtime heap corruption.

 4. Dereferencing NULL: Forgetting to check if ptr == NULL before storing data will cause immediate segmentation faults if memory was exhausted.


Practice Session for Beginner Students

Review these dry runs, MCQs, and university lab questions.

Part 1: Spot the Bug & Predict the Output

Problem 1: What is dangerous about the following code snippet?


int *ptr = (int*) malloc(sizeof(int));
*ptr = 100;
free(ptr);
printf("%d", *ptr);
							

Answer & Explanation: Dangling Pointer access! The memory was deallocated by free(ptr). Reading from *ptr afterward invokes undefined behavior (may print garbage, crash, or access recycled memory).

Part 2: Multiple Choice Questions (BCA Exam Preparation)

Q1. What return type is produced by malloc() and calloc()?
A) int*
B) void* (Generic pointer)
C) char*
D) NULL
Correct Answer: B) void* (A generic pointer that must be cast to the desired data type).

Q2. What is the effect of realloc(ptr, 0);?
A) Expands memory to 0 bytes
B) Equivalent to calling free(ptr)
C) Compilation error
D) Does nothing
Correct Answer: B) Equivalent to calling free(ptr).

Part 3: Frequently Asked University Viva Questions

1. Why is calloc() slower than malloc()?
Answer: calloc() performs two operations: it calculates the total bytes and then writes zeros across all allocated bytes in memory, whereas malloc() simply reserves the memory block without initializing it.

2. What happens if malloc() fails to find available memory on the heap?
Answer: It returns a NULL pointer. Programs must always check if (ptr == NULL) before accessing memory.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!