Is there any definite reason for the downward implementation stack an upward implementation of heap?
Is there any chance for overlapping of those?(definetly there is mechanism to prevent that but what if i continously call malloc)
Is there any definite reason for the downward implementation stack an upward implementation of heap?
Is there any chance for overlapping of those?(definetly there is mechanism to prevent that but what if i continously call malloc)
I suspect it's historical. Back in the 70's, chips like the 8080 booted from zero, so you put code (in ROM) there. Logically, you then put RAM at high memory. Both areas expanded towards the middle, as the software bloated (as it always does :) The first systems didn't have a heap (being programmed in assembler, not C). So data was assigned downward from the top, statics first, & let the stack use the rest until we ran out of RAM. When that happened, fit a larger RAM, & encroach toward lower addresses.
Depends how the subroutine call and return machine instructions are implemented. If the call is implemented as
and return as
Then it is natural to put the stack on the top growing downwards. Also any data push/pop should be done in the same order.
However, if the subroutine call is
Then the stack should start on the bottom and grow upwards.
There no risk for overlap in a properly designed system.
When the stack grows downward and heap upwards, the dynamic memory manager keeps track of the highest address used and malloc checks if a new value would increase above the stack pointer. In that case the malloc refuses the allocation and returns a null pointer. It is up to the application to check what to do, if malloc returns NULL.
On the other hand if the stack grows too much, eg. due to out of control recursion, the compiler can insert at the function entry a code that calculates the stack space required for the function local variables (and possibly interrupt service routine stack space) and compare this to the top of heap. If this would overlap, something would have to be done, such as abort the program or in C++ case possibly throw an exception.
Paul
Think about it.
--
Different processors grow their stacks in different directions. I think downward is more common, but it's certainly not ubiquitous.
If you wrote me a malloc that could cause the heap to grow out of it's assigned space I would call it 'broken'. If you wrote me an application that grew the stack out of it's assigned space, I'd call that 'broken', too.
That doesn't mean it doesn't happen (even in my code).
-- Tim Wescott Control systems and communications consulting
ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.