February 04, 2011 at 07:24 Tags Articles , Assembly

I've noticed more than once that some programmers are confused about the direction in which the stack grows on x86, and what "top of the stack" and "bottom of the stack" mean. It appears that this confusion is caused by a basic mismatch in the way people are used to thinking about stacks, and in the way the stack on x86 actually behaves .

In this article, I intend to resolve this confusion with a few helpful diagrams.

The stack analogy Back to the basics. The stack analogy is sometimes demonstrated to new students of computing with a stack of plates. You push a plate onto the stack and pop a plate off the stack. The top of the stack is where your next plate goes when pushing, and from where you take a plate when popping.

Hardware stacks In computers, the stack is usually a specially treated region of memory. In the abstract sense, the analogy applies - you push data by placing it on the top of the stack, and pop data by taking it from the top of the stack. Note that this doesn't address the issue of where the top of the stack is located in memory.

The stack in x86 Herein lies the source of the confusion. Intel's x86 architecture places its stack "head down". It starts at some address and grows down to a lower address. Here's how it looks: So when we say "top of the stack" on x86, we actually mean the lowest address in the memory area occupied by the stack. This may be unnatural for some people . As long as we keep the diagram shown above firmly in mind, however, we should be OK. While we're at it, let's see how some common idioms of x86 assembly programming map to this graphical representation.

Pushing and popping data with the stack pointer The x86 architecture reserves a special register for working with the stack - ESP (Extended Stack Pointer). The ESP, by definition, always points to the top of the stack: In this diagram, address 0x9080ABCC is the top of the stack. The word located in it is some "foo" and ESP contains the address 0x9080ABCC - in other words, points to it. To push new data onto the stack we use the push instruction . What push does is first decrement esp by 4, and then store its operand in the location esp points to. So this: push eax Is actually equivalent to this: sub esp, 4 mov [esp], eax Taking the previous diagram as the starting point, and supposing that eax held the venerable value 0xDEADBEEF , after the push the stack will look as follows: Similarly, the pop instruction takes a value off the top of stack and places it in its operand, increasing the stack pointer afterwards. In other words, this: pop eax Is equivalent to this: mov eax, [esp] add esp, 4 So, again, taking the previous diagram (after the push ) as a starting point, pop eax will do the following: And the value 0xDEADBEEF will be written into eax . Note that 0xDEADBEEF also stays at address 0x9080ABC8 , since we did nothing to overwrite it yet.