Heap overflow vs stack overflow

data structuresheapstackstackoverflow

So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?

Best Answer

Obviously, storing X byte of data is going to reduce the amount of free memory by at least X bytes, no matter where you put it.

big objects should be allocated to the heap

I don't think that this is the main distinction to draw.

If you need data to be accessible outside of the current stack frame (for example as a global variable, or to pass it to another thread), you cannot put it into the stack.

The stack shrinks when a subroutine returns, so all data stored in its stack frame is lost.

Data on the heap stays "alive" until you de-allocate it.

Beyond that, because stack memory is generally much more limited than heap memory in "real life" (not just two unlimited sections growing towards each other like you alluded to in your question), you may want to put anything large on the heap, even if you could put it on the stack. For example, Java places everything in the heap. The downside is more complex memory management.