I'm new to assembly language and I was wondering about local variables, why do we (or the compilers) preserve a space for them on the stack usually by decrement the "ESP" register at the prologue of the procedure and as the procedure ends we assign the "ESP" it's old value again. like this code sample :
; a procedure that create the stack frame then assign 10, 20 values for two local variables then return to caller
two_localv_proc PROC
push ebp
mov ebp,esp
sub esp,8
mov DWORD PTR [ebp-4],10
mov DWORD PTR [ebp-8],20
mov esp,ebp
pop ebp
ret
two_localv_proc ENDP
the last code snippet will do exactly if we removed the (sub esp,8) line and the (mov esp,ebp) line, to be as this
two_localv_proc PROC
push ebp
mov ebp,esp
mov DWORD PTR [ebp-4],10
mov DWORD PTR [ebp-8],20
pop ebp
ret
two_localv_proc ENDP
so why we (or the compilers) do such behavior! , why don't we just use the stack memory to store our local variables as long as the "ESP" pointer will not affected by storing values on the stack with codes like:
mov DWORD PTR [ebp-8],20