Allocation and Deallocation on the Heap
You'll learn how programs request and release heap memory, and why managing it carefully matters.
How Heap Allocation Works
When your program needs memory whose size or lifetime isn't known at compile time, it requests space from the heap using allocation functions. In C, you call malloc(size) to request a block of bytes; in C++, you use new Type. The memory manager searches for a suitable free block, marks it as "in use," and returns a pointer to it.
Think of the heap like a parking lot: when you arrive, the attendant finds an empty spot that fits your car and gives you a ticket (the pointer).
Deallocation Returns Memory
When you're done with heap memory, you must explicitly release it using free(pointer) in C or delete pointer in C++. This tells the memory manager: "This block is available again." Forgetting to deallocate causes memory leaks—your program holds onto memory it no longer needs, eventually exhausting available space.
Continuing the parking analogy: if you never return your parking ticket and leave your car there forever, the lot fills up even though many cars aren't actually being used.
Heap Fragmentation
Over time, allocations and deallocations create fragmentation. External fragmentation occurs when free memory exists but is scattered in small, non-contiguous chunks—there might be enough total space, but no single block large enough for your request. Internal fragmentation happens when allocated blocks are larger than needed, wasting space within the block itself.
The memory manager uses strategies like maintaining free lists (tracking available blocks) and coalescing (merging adjacent free blocks) to combat fragmentation, but perfect efficiency is impossible in general-purpose systems.
Key Takeaway: Heap allocation (malloc/new) requests variable-lifetime memory, deallocation (free/delete) releases it, and fragmentation degrades efficiency over time—careful memory management is essential.