Reputation: 61
Why is it that when you push a value onto the stack, the ESP register is decreased (as opposed to increased) and when you pop a value, the ESP register is increased (as opposed to decreased)? This is counter intuitive to me at this point.
Upvotes: 2
Views: 244
Reputation: 71546
With a single memory system as it was, and still is in many environments programmers face, you would have the heap grow up from lower addresses to higher addresses and the stack grow down from the top of memory high addresses down to lower addresses, maximizing the use of that memory without collision. If they both grew up there would be a need to have them leapfrog in some painful and ugly way, or one or the other would be restricted despite having free memory available. On a number of processors, you are free to re-write malloc or create your own and have the stack grow up (some instruction sets can arbitrarily go either way some cannot without extra effort) and the heap down. Better to go with the flow though and have the stack grown down and heap grow up.
Upvotes: 1
Reputation: 62058
It's more or less an arbitrary design choice. The stack will function equally well if the stack pointer increments on a push and decrements on a pop. In some languages text is written right to left instead of left to right, and a specific direction doesn't really make a language better or worse.
Upvotes: 1
Reputation: 30439
Thats because that way the stack "grows" from top to bottom, opposed to the heap, which is allocated bottom up.
On architectures with a limited address space this was a design decision, you can use them both more flexible - only the sum of both allocated memory regions must not exceed a certain limit.
Nowadays the stack and heap address space is kept in separate memory regions anyway, but they decided to keep the backwards growing stack.
Upvotes: 7