heap-memoryheapconcept

What's the relationship between those two “heaps”?


There're two concepts named "heap" in computer science. One is the memory pool used in memory management, the other is an algorithm.

I know they are different, but what's the relationship between them? Or they just happen to get the same name?


Solution

  • As far as I know, they just happen to have the same name.

    One 'heap' is the data structure that contains, at its head, the greatest element of a collection. Since its children just have to be smaller than it, it is a semi-sorted collection. This is more efficient than maintaining a fully sorted list in certain circumstances, such as when you're commonly interested in only the largest element. http://en.wikipedia.org/wiki/Heap_(data_structure)

    The other 'heap' is the place in memory besides the stack data can be stored. The problem with data stored in the stack is that it will be freed, and thus lost, when the function returns, and on top of that the stack can only hold so much before overflowing. The 'structure' of the heap is usually a linked list of free data segments - malloc looking for a data segment that satisfies the size requirements, marking it as in use and returning it, whereas free looks for the header for that data segment in the heap, marks it as unused and puts it back in the linked list of free data segments. (Other optimizations include things like having dedicated linked lists for certain chunk sizes.)

    As you can see - not related at all!