4 ms·
The stack includes scratch-pad memory that is temporarily allocated for local variables. The heap is 'permanent' memory that hangs around beyond function calls.
by GnarfGnarf 16y ago
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).