Dynamic Memory Allocation
Requesting memory while your program is running — malloc, calloc, realloc, and free.
Why Dynamic Memory?
Regular arrays need a fixed size decided at compile time. Dynamic memory allocation lets you request memory AT RUNTIME, based on actual need — e.g. asking the user how many students there are, then allocating exactly that much space.
malloc, calloc, realloc
malloc(n) allocates n bytes of uninitialized memory. calloc(n, size) allocates memory for n elements and initializes it all to zero. realloc(ptr, newSize) resizes previously allocated memory, keeping existing data where possible.
int *arr = (int*) malloc(5 * sizeof(int));
if (arr == NULL) { /* allocation failed */ }
arr[0] = 10;
free(arr); // must free when doneWhy free() Matters
Memory allocated with malloc/calloc doesn't get cleaned up automatically like local variables do — you MUST call free() when you're done, or the memory stays reserved for the program's entire lifetime, causing a 'memory leak'.
🌍 Real-World Use
Any program handling an unknown amount of data at start-time — like a contact book app that grows as you add contacts, or a text editor loading a file of unknown size — relies on dynamic memory allocation.
💡 Pro Tip
ALWAYS check if malloc/calloc returned NULL before using the pointer — if the system runs out of memory, malloc returns NULL instead of crashing, and using a NULL pointer without checking will crash your program anyway, just with a more confusing error.
🧪 Quick Self-Test
Check what you just learned — no pressure, just practice.
1. Which function allocates memory AND initializes it to zero?
2. What happens if you forget to call free() on allocated memory?