I'm trying to understand better how the stack works and I wrote this program.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define SIZE 0
void proof(){
unsigned int buf[SIZE];
unsigned int i = 0;
printf("buf is at %X\n", (unsigned int)buf);
//printf("return address is at buf[size+4] %X\n", (unsigned int)buf[SIZE+4]);
//printf("return address is at buf[size]+16 %X\n", (unsigned int)&buf[SIZE]+12);
printf("Effective return address %p\n", __builtin_return_address(0));
printf("Proof address %p\n",&proof);
}
void main(){
proof();
}
I have imagined the stack like this:
return address |
---|
previous frame pointer |
the variable i |
buf[SIZE] |
From the output I can see that the return address of this function is placed in buf[size+4]
but I don't get why. Shouldn't the return address always be at ebp+4
? I have tried taking the address of ebp
with gdb but it is not the same I have obtained from my code. Moreover, in this case if the stack is like I have imagined, shouldn't the return address be at &buf[SIZE]+12
since we are moving in multiply of 4?