Because of the way computer programs are structured, it is very convenient to have an area or memory that can start being used whenever you enter a code segment and stop being used whenever you exit that code segment. This is stack memory.
But sometimes you need to start using some memory to store something that you’ll still need even after exiting the current code segment. It can’t go in stack memory, because it would be automatically deallocated. So we also have heap memory that is more flexible but much more complicated to manage.
These aren’t different physical components — a program just uses a certain range of memory addresses as its stack and another as its heap. In fact, those aren’t the only memory segments it will have, and there’s no reason it couldn’t have multiple stacks and heaps. (A multi threaded program will definitely have multiple stacks.) Modern virtual memory is frightfully complicated, but most programmers most of the time only need to worry about whether they want space allocated on the current stack or the standard heap.
Latest Answers