An Example of Using the Stack

This is a trivial example of how to pass and receive parameters, which is used to document where the stack pointer and base pointer are at the end of each instruction.

The example is 32-bit non-optimized code.

The subroutine, SUB, is designed to return the difference obtained by subtracting the second parameter from the first.

First, the relevant C code:

(  main  )                 ( sub )
    .
z=sub(A,B);                int sub(int x, int y)
    .                        {
    .                        return x-y;
    .                        }

Next, the assembler code

    .          ( i ) initial condition
  PUSH B     ; (01)             SUB:    PUSH EBP         ; (04)
  PUSH A     ; (02)                     MOV  EBP,ESP     ; (05)
  CALL SUB   ; (03)                     SUB  ESP,nn      ; (06)
  ADD  ESP,8 ; (12)                      .
  MOV  Z,EAX ; ( f ) final condition     .   ( NOTE )
                                         .
                                        MOV  EAX,[EBP+8] ; (07)
                                        SUB  EAX,[EBP+12] ; (08)
                                         .
                                        MOV  ESP,EBP       (09)
                                        POP  EBP           (10)
                                        RET                (11)

Note: At this point, the stack frame is established. If another, lower-level routine is called, the code to do so will look like the code seen in main, and a new stack frame will be established by that routine as soon as it receives control.

The new frame will be just below the current one.


[Back: Single Stack Frame]
[Next: Stack Example]