Dynamic Memory Allocation (DMA): malloc, calloc, realloc & free
Unit 5: Searching, Sorting, Dynamic Memory & File Handling • Problem 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
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.
2. The 4 DMA Functions in <stdlib.h>
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));`
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));`
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.
Releases previously allocated heap memory back to the Operating System.
Prevents Memory Leaks. Does NOT delete the pointer variable itself!
3. The 2 Critical DMA Pitfalls: Memory Leaks & Dangling Pointers
Occurs when heap memory is allocated via malloc/calloc but never released with `free()`. Over time, server RAM progressively exhausts until the system crashes.
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);`!
| Function | Arguments Taken | Initial Byte State | Return on Failure | Primary Architectural Purpose |
|---|---|---|---|---|
| malloc(size) | 1: Total bytes required | Contains uninitialized random garbage | NULL | Fastest raw runtime heap memory allocation |
| calloc(n, size) | 2: Element count & byte size | Cleanly initialized to strictly ZERO (0) | NULL | Safe allocation for arrays needing zero initialization |
| realloc(ptr, size) | 2: Old pointer & new byte size | Preserves existing bytes, expands/shrinks | NULL | Resizing dynamic arrays as data scales at runtime |
| free(ptr) | 1: Heap pointer to release | Memory returned to OS pool | void (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;
}🎯 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.