I wrote a small program to understand the structure of stack.
#include <stdio.h>
void function(int a, int b, int c) {
char buffer1[5];
char buffer2[10];
int *ret = buffer1 + 13;
(*ret) += 8;
}
int main() {
int x = 0;
function(1,2,3);
x = 1;
printf("x = %d\n",x);
return 0;
}
till now I have learnt that the stack follows below pattern
------------------
| arguments | High
------------------
| return address |
------------------
| ebp |
------------------
| buffer1 |
------------------
| buffer2 | Low
------------------
I have also learnt that if we allocate 5 bytes of data, program allocates 8 (because it has to be a multiple of word size).
Dump of assembler code for function function
:
0x08048414 <+0>: push %ebp
0x08048415 <+1>: mov %esp,%ebp
0x08048417 <+3>: sub $0x20,%esp
0x0804841a <+6>: lea -0x9(%ebp),%eax
0x0804841d <+9>: add $0xd,%eax
0x08048420 <+12>: mov %eax,-0x4(%ebp)
0x08048423 <+15>: mov -0x4(%ebp),%eax
0x08048426 <+18>: mov (%eax),%eax
0x08048428 <+20>: lea 0x8(%eax),%edx
0x0804842b <+23>: mov -0x4(%ebp),%eax
0x0804842e <+26>: mov %edx,(%eax)
0x08048430 <+28>: leave
0x08048431 <+29>: ret
End of assembler dump.
Now I run the program under gdb, I get,
(gdb) x/x $ebp
0xbffff318: 0xbffff348
(gdb) x/x buffer1
0xbffff30f: 0xfc73e461
(gdb) x/x buffer2
0xbffff305: 0x0108049f
Here's my doubt, how can the difference between buffer1
and buffer2
be 10
, when everything is allocated in a multiple of wordsize.
Also how is there a difference of 9
between %ebp and buffer1
?
What exactly is happening here ?
Note :
- Consider stack grows from High to Low
- Wordsize = 4
I'm using Intel processor, Ubuntu 12.04, 32bit and use
gcc -o stack -g -fno-stack-protector -O0 main.c
to build.