To understand memory management, you must first distinguish between Static Allocation (Stack) and Dynamic Allocation (Heap).
Most variables you have used so far are stored on the Stack. Their size must be known at compile-time, and they are deleted automatically when the function ends.
The Heap is a large pool of memory that stays allocated until you explicitly free it. This allows you to create data structures like Linked Lists or arrays whose size is determined by user input while the program is running.
All dynamic memory functions are located in the <stdlib.h> header file. There are four primary functions you must master:
malloc stands for "Memory Allocation." It reserves a single block of memory of a specified size in bytes.
Crucial Note: It returns a void* (a pointer to an unknown type), so you should cast it to your desired type. It also does not clear the memory; it will contain "garbage values."
calloc is similar to malloc but is used to allocate multiple blocks of memory. It takes two arguments: the number of elements and the size of each.
Key Difference: It initializes all allocated memory to zero.
If the memory previously allocated is insufficient or more than required, realloc changes the size of the memory block without losing the old data.
This is the most critical function. It releases the memory block back to the heap. If you do not call free, your program will keep consuming memory until the system runs out—this is known as a Memory Leak.
When working with the heap, you must follow a strict 4-step process to prevent crashes:
Dynamic memory is powerful, but dangerous. Watch out for these three bugs:
free(). In long-running applications (like servers), this will eventually crash the computer.ptr when malloc returned NULL).| Feature | malloc() | calloc() |
|---|---|---|
| Initialization | Garbage values (Fast). | Zero-initialized (Slower). |
| Number of Args | 1 (Total bytes). | 2 (Elements, size per element). |
| Use Case | Large single blocks. | Arrays or cleared memory. |
realloc, always assign the result to a temporary pointer. If realloc fails, it returns NULL, but the original memory is still valid. If you overwrite your original pointer with NULL, you will never be able to free the old memory!