Processes & the Process Abstraction

the heap

Imagine a big communal supply room where, in the middle of cooking, you can go grab as much counter space as you suddenly need, use it, and then return it when you are done. You do not have to declare upfront how much you will need. The heap is the region of a process's memory used for dynamic allocation: memory the program requests at run time, in amounts it may not know in advance, and gives back when finished.

When a program calls something like malloc in C or new in C++ (or when a higher-level language creates an object), it is asking the heap manager for a block of memory of a certain size. The manager finds a free block, marks it as in use, and hands back its address; later the program frees it (or a garbage collector reclaims it) so the space can be reused. The heap typically sits above the data and BSS segments and grows upward toward the stack as more memory is requested. Because allocations and frees happen in any order, the heap can become fragmented, with free gaps too small to reuse, which is one reason heap management is more complex than the stack's simple grow-and-shrink.

The heap is where data lives when it must outlast the function that created it, or when its size is only known at run time, like a list that grows as a user types. The cost is responsibility: in manual-memory languages, forgetting to free leaks memory, and freeing twice or using freed memory causes corruption and crashes. A common misconception is that 'the heap' is a data-structure heap (the kind used in priority queues); the memory heap is unrelated and just borrows the word.

Calling p = malloc(40) asks the heap for 40 bytes; the program uses p, then calls free(p) to return it. If it never calls free, those 40 bytes are leaked: reserved but unreachable for the rest of the program's life.

Ask with malloc, return with free; forgetting to return leaks memory.

Heap allocation is flexible but slower and trickier than stack allocation; bugs like leaks, double-free, and use-after-free are heap problems, not stack ones.

Also called
dynamic memoryfree store堆積動態記憶體