chloe.t
chloe.t

Reputation: 43

Stack push and pop in assembly language for x86 processors

I am learning assembly language for x86 processor, there are 2 questions I would like you to take a look for me if I answered it correctly.

  1. Which statement is true about what will happen when the example code runs?
 1: main PROC
 2:      mov edx, 0
 3:      mov eax, 40
 4:      push eax
 5:      call Ex5Sub
 6:      INVOKE ExitProcess, 0
 7: main ENDP
 8: 
 9:Ex5Sub PROC 
10:      pop eax
11:      pop edx 
12:      push eax
13:      ret 
14:Ex5Sub ENDP

a. EDX will equal 40 on line 6
b. The program will halt with a runtime error on Line 13
c. EDX will equal 0 on line 6
d. The program will halt with a runtime error on Line 11

My Answer: (d) as the there is only one element 40 pushed into stack and there is no other element to be popped.

  1. Is the same as second questions posted in this link Assembly Language 2 Book on Push and Pop. I do not have enough reputation to put comment and ask about it. The person who answered to this question said (d) but I do not understand why it is (d) as from what I learned from book is that after pop eax is executed, the esp will be incremented and point to the previous value, so when it is ret, it should be 10.

Your patience in explaining to me would be appreciated. Thank you

Upvotes: 0

Views: 4089

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61969

The answer for #1 will actually help you understand #2 without having to post a comment to that other question.

Sorry, but (d) is wrong. Your assumption that there is only one element pushed into the stack is incorrect. The push eax instruction on line 4 places one element into the stack, but the call Ex5Sub instruction on line 5 places one more element into the stack: the return address for the subroutine. That's what call instructions do: they push a return address into the stack, and then they jump to the destination. The return address is always the address of the instruction immediately following the call instruction, so in this case, the return address is the address of line 6.

So, the subroutine pops the return address from the stack, pops 40 from the stack into edx, puts the return address back in the stack, and returns. Therefore, edx will hold 40 upon returning from the subroutine, which means that (a) is correct.

Upvotes: 3

Related Questions