The name is a loose metaphor
Heap memory is usually explained by its layout: a heap is a pile of blocks with no set order, while the stack follows a strict last-in, first-out rule. The name describes a way of picturing memory rather than a formal rule. There is no single documented origin for the word in this sense, so treat the explanation below as the common reading, not settled history.
The usual explanation: a pile versus a stack
Picture a stack of plates. You add to the top and take from the top, so the order is always clear. A stack in memory works the same way: each function call adds a frame, and the newest frame is removed first.
A heap is more like a pile of things. You can grab an item from anywhere, and you can put things back into any gap. Heap memory works similarly. Your program asks for blocks of different sizes, frees them in any order, and the allocator fits each new request into whatever free space it has.
That contrast is the idea most often given for the name. It is a description, though, not a definition.
The word has a precise meaning elsewhere
“Heap” also names a data structure, usually a binary heap. It is a tree in which each parent is at least as large as its children in a max-heap, or at most as large in a min-heap. That rule is strict, so the data structure is not a loose pile. It uses the word with its own meaning.
What the name does and doesn’t tell you
The name doesn’t give you rules for using heap memory. The practical rules are these:
- You request heap memory at runtime with
newormalloc. - The memory stays reserved until you release it with
deleteorfree. - If you forget to release it, the memory leaks.
Why heap memory outlives a function
Stack memory ends when its function returns. Heap memory can outlive the function that created it, which is useful when a function builds something and hands it back to its caller.
int* makeCounter()
{
int* counter = new int(0); // heap memory: survives the return
return counter;
}
int main()
{
int* count = makeCounter(); // main now owns the memory
*count += 1;
delete count; // main must release it
return 0;
}
If makeCounter returned a pointer to a local int instead, the pointer would be dangling as soon as the function returned. The heap version is safe to return, as long as someone eventually deletes it.
For the stack side of the contrast, read about c heap vs stack.
Summary
The name “heap” describes a loose, unordered area, and the usual explanation is a useful picture. For the practical side, remember that heap memory is yours to request and yours to release.