NBC 103 • Unit 516 min readHigh Exam Frequency

Dynamic Memory Allocation (DMA): malloc, calloc, realloc & free

Unit 5: Searching, Sorting, Dynamic Memory & File HandlingProblem Solving Using C

👨‍🏫 Professor's Mental Model: Purchasing Freehold Land vs Renting Banquet Hall On-Demand

Static Memory Allocation ek permanent makan khareedne jaisa hai: compile-time par decide kar liya ki 100 rooms chahiye; agar 5 guests aaye toh 95 rooms waste honge, aur 105 guests aaye toh log bahar reh jayenge (Buffer Overflow)! Dynamic Memory Allocation (DMA) ek hotel banquet hall rent karne jaisa hai: jitne guests hain utni jagah Heap par lo (malloc/calloc), party badh jaye toh hall expand karo (realloc), aur party khatam hone par hall khaali karke chabi lauta do (free)! Agar lautaana bhool gaye toh Memory Leak ho jayega!

Academic Lecture Notes & Solved Study Pages

Unit 5 • Core Concepts, Step-by-Step Proofs & Notebook Solutions

3 Notebook Pages
NOTEBOOK PAGE 1 OF 3

1. Limitations of Static Memory & The 4 Memory Segments in C

RAM allocated to a running C process is partitioned into 4 distinct segments: 1. Code Segment (Text): Read-only instructions compiled from source. 2. Data Segment: Global and static variables initialized at startup. 3. Call Stack: Automatically manages local variables and function activation frames (LIFO, fixed maximum size). 4. Heap Segment: Vast, unmanaged pool of RAM available for dynamic, runtime allocation controlled directly by the programmer via pointers.

NOTEBOOK PAGE 2 OF 3

2. The 4 DMA Functions in <stdlib.h>

1. malloc(size_in_bytes):

Allocates a contiguous block of raw memory on the Heap.

Returns a generic `void *` pointer. Returns `NULL` if heap is exhausted.

CRITICAL: Allocated bytes contain RANDOM GARBAGE VALUES!

Syntax: `int *ptr = (int *)malloc(10 * sizeof(int));`

2. calloc(num_elements, size_of_each):

Contiguous Allocation. Takes two arguments and allocates `n * size` bytes.

CRITICAL DISTINCTION: Automatically initializes ALL allocated bytes to strictly ZERO (0)!

Syntax: `int *ptr = (int *)calloc(10, sizeof(int));`

3. realloc(ptr, new_byte_size):

Dynamically resizes a previously allocated heap memory block without losing existing data.

Can expand or contract memory. If current location cannot expand, it moves the block to a new heap location.

4. free(ptr):

Releases previously allocated heap memory back to the Operating System.

Prevents Memory Leaks. Does NOT delete the pointer variable itself!

NOTEBOOK PAGE 3 OF 3

3. The 2 Critical DMA Pitfalls: Memory Leaks & Dangling Pointers

Memory Leak:

Occurs when heap memory is allocated via malloc/calloc but never released with `free()`. Over time, server RAM progressively exhausts until the system crashes.

Dangling Pointer:

A pointer that continues pointing to a memory address after `free(ptr)` has deallocated it. Dereferencing a dangling pointer leads to memory corruption.

BEST PRACTICE: Always set `ptr = NULL;` immediately after `free(ptr);`!

Master DMA Comparison: malloc() vs calloc() vs realloc()
FunctionArguments TakenInitial Byte StateReturn on FailurePrimary Architectural Purpose
malloc(size)1: Total bytes requiredContains uninitialized random garbageNULLFastest raw runtime heap memory allocation
calloc(n, size)2: Element count & byte sizeCleanly initialized to strictly ZERO (0)NULLSafe allocation for arrays needing zero initialization
realloc(ptr, size)2: Old pointer & new byte sizePreserves existing bytes, expands/shrinksNULLResizing dynamic arrays as data scales at runtime
free(ptr)1: Heap pointer to releaseMemory returned to OS poolvoid (None)Preventing catastrophic system memory leaks

Interactive Tested Code Example

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

int main(void) {
    int initial_size = 3, expanded_size = 5;

    // 1. Allocate Heap Array with calloc (Zero-Initialized)
    int *arr = (int *)calloc(initial_size, sizeof(int));
    if (arr == NULL) {
        printf("Heap allocation failed! Out of Memory.\n");
        return 1;
    }

    for (int i = 0; i < initial_size; i++) arr[i] = (i + 1) * 10;
    printf("Initial Heap Array: ");
    for (int i = 0; i < initial_size; i++) printf("%d ", arr[i]);
    printf("\n");

    // 2. Dynamically Expand Array with realloc
    int *temp = (int *)realloc(arr, expanded_size * sizeof(int));
    if (temp == NULL) {
        free(arr);
        return 1;
    }
    arr = temp;
    arr[3] = 40; arr[4] = 50;

    printf("Resized Heap Array: ");
    for (int i = 0; i < expanded_size; i++) printf("%d ", arr[i]);
    printf("\n");

    // 3. Prevent Memory Leak and Dangling Pointer
    free(arr);
    arr = NULL; // Safe Sentinel
    printf("Memory freed and pointer neutralized successfully.\n");
    return 0;
}
💡 Note:Demonstrates safe dynamic memory lifecycle: allocation with calloc, NULL verification, resizing with realloc, and deallocation with free() followed by NULL assignment.

🎯 University Exam Scoring Blueprint

  • In university exams, always check if (ptr == NULL) immediately following malloc/calloc calls.
  • Highlight the primary difference: malloc leaves garbage, calloc initializes to zero.
  • Define Memory Leak and write a 2-line example demonstrating how setting ptr = NULL after free() fixes dangling pointers.

Top Viva Questions on Dynamic Memory Allocation (DMA): malloc, calloc, realloc & free

2 Questions
1

What does malloc(0) return in C?

2

Can memory allocated with malloc() be freed partially?