Python Dynamic Memory: malloc, calloc, realloc & free
Heap memory allows requesting dynamic RAM buffers from the OS at runtime. malloc() allocates uninitialized memory, calloc() zero-initializes memory, realloc() resizes buffers dynamically, and free() releases heap blocks back to the OS.
"Stack memory is reserving a table at a cafe that is cleared as soon as you leave; heap memory is renting a storage unit where you must explicitly return the physical key (free()) when finished."
Deep Dive: How It Works
Heap vs Stack: Stack is automatic and fast; heap is manual and dynamically sized.
realloc(): Expands or contracts existing buffers while preserving previous contents.
Dangling Pointers: Always set pointers to NULL after calling free(ptr).
Syntax Blueprint
int *buf = (int*)malloc(N * sizeof(int));
if (buf) {
buf[0] = 42;
free(buf);
buf = NULL;
}Allocate heap memory, check for non-NULL, use buffer, free memory, and set pointer to NULL.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting to free heap memory in error early-return branches.Why it happens: Returning early skips the free() statement at the end of the function, creating persistent RAM leaks.
How to fix: Ensure every return pathway cleans up allocated resources.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Confirm Clean Heap Teardown
Print "Memory Freed: SUCCESS\n" after freeing the array.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.