Why does leave do “mov esp,ebp” in x86 assembly

assemblyx86

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…

Best Answer

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.