› Module 10: Dynamic Memory Management › 10.1 Stack vs Heap: Memory Segments
M O D U L E

Module 10: Dynamic Memory Management

Allocating and releasing memory at runtime instead of relying only on fixed, compile-time sizes.

10.1 Stack vs Heap: Memory Segments

A running C program's memory is divided into segments. The Text segment holds compiled instructions. The Data/BSS segment holds global and static variables. The Stack holds function call frames and local variables — it grows and shrinks automatically and very fast, but its size is limited. The Heap is a large pool available for manual allocation at runtime via malloc()/calloc(), and it persists until explicitly freed — giving flexibility at the cost of manual management.

High Address Stack (local variables, function frames - grows downward) ↕ free memory ↕ Heap (malloc/calloc dynamic memory - grows upward) BSS / Data (global & static variables) Text / Code (compiled instructions, read-only) Low Address
The four memory segments of a running C process.

10.2 malloc, calloc, realloc, and free

malloc(size) reserves 'size' bytes of uninitialized heap memory and returns a void* (or NULL on failure). calloc(n, size) allocates n blocks of 'size' bytes each and zero-initializes them. realloc(ptr, newSize) resizes a previously allocated block, preserving existing content where possible. free(ptr) returns the memory to the heap — forgetting to call it causes a memory leak, and using memory after freeing it (a 'dangling pointer') is undefined behaviour.

int *arr = (int*) malloc(4 * sizeof(int));
if (arr == NULL) { /* allocation failed */ }
arr[0] = 100;
arr = realloc(arr, 8 * sizeof(int));   // grow to 8 ints
free(arr);                            // release back to heap
arr = NULL;                           // avoid dangling pointer
int *p = malloc(4*sizeof(int)); OS/Heap manager reserves 16 bytes p stores the starting address of that block free(p); // returns memory // to the heap when done
Requesting and releasing a block of heap memory.
MODULE COMPREHENSIVE QUIZ

Module 10 Final Quiz

Test your understanding across all 2 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 10 Final Quiz →
Yukti Mascot