Mastering memory management is what separates C programmers from C users. Learn to allocate, manage, and free memory safely—the foundation of systems programming.
Every program has two main memory regions. Understanding them is fundamental.
| Feature | Stack | Heap |
|---|---|---|
| Size | Small (MBs) | Large (GBs) |
| Allocation | Automatic | Manual (malloc) |
| Deallocation | Automatic (Scope End) | Manual (free) |
| Speed | Very Fast | Slower |
| Lifetime | Function Scope | Persistent until free |
Allocates a block of uninitialized memory.
Allocates memory and initializes all bytes to zero. Slightly slower than malloc.
Resizes a previously allocated block. Can shrink or expand.
Occurs when you allocate memory but forget to free it. The memory remains occupied until the program exits.
A pointer that points to memory that has been freed. Dereferencing it causes undefined behavior (crash).
Over time, frequent allocations and deallocations leave small gaps in the heap, making it impossible to allocate large contiguous blocks even if total free memory is sufficient.
Calling free() on the same pointer twice. This corrupts the heap management data structures and crashes the program.
The ultimate tool for detecting memory leaks and errors.