

Ask HN: Beginners guide to stacks and heaps? - kevinburke

I've tried to find a good introduction to stacks and heaps online, but most of them are either incomplete or too difficult to follow. Is there any relation between memory heaps and the heap data structure? How are the stack and the heap related? Also, I have an idea of what garbage collection is, but how does garbage collection work in practice? Thanks for your help.
======
GnarfGnarf
The stack includes scratch-pad memory that is temporarily allocated for local
variables. The heap is 'permanent' memory that hangs around beyond function
calls.

Advantages of the stack: you don't have to explicitly ask for it, it's
allocated automatically for you, and you don't have to worry about releasing
it. Exiting from a function magically frees it up.

Disadvantage of the stack: the size of the stack is limited, and since it only
exists while you are in a function, the data vanishes after you exit the
function.

Advantages of the heap: The amount of memory you can acquire is huge, only
limited by the total size of virtual memory in your system. Also, this memory
remains allocated as long as you want.

Disadvantages of the heap: you have to explicitly ask for heap memory, and you
have to remember to release it, otherwise you get memory leaks. If you ask for
a lot of small lumps of memory, you can get fragmentation.

In higher-level languages, you don't have to worry about releasing memory. The
OS figures out when you don't need it anymore, and releases it for you.
(That's my understanding of garbage collection).

