63
votes

It's said that the leave instruction is the same as :

mov esp,ebp
pop ebp

But what is mov esp,ebp here for? It doesn't seem valid to me...

3

3 Answers

92
votes

mov esp,ebp sets the stack pointer to the base frame address, effectively releasing the whole frame. (Don't forget that this is Intel syntax, the destination comes first.) If you didn't do it, once you call ret, you would still be using the called function's stack frame with your calling function, with crashtastic consequences.

4
votes

I think your issue is the fact that there are two different ways of writing x86 assembly. One is the AT&T notation and the other is the Intel notation. The order of the arguments to an instruction are reversed in Intel notation as opposed to AT&T. Your version of the assembly appears to be in Intel notation, which means that mov esp, ebp actaully moves the value in ebp to esp. In the more logical (in my opinion) AT&T notation it would be mov %ebp, %esp.

2
votes

The compiler use this instruction to free the used space by the function in the stack, the leave instruction has the same behavior as mov esp, ebp with pop ebp.