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.
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