Hi, I wrote a simple C program to test the memory allocation for local variables.
#include
int main(int argc, char **argv) {
int x=10;
return 0;
}
But when i try to disassemble the program using gdb, it shows that 16 bytes are being reserved for local variables on the stack, although i declared a single integer variable which is supposed to take only 4 bytes.
Can anyone tell, why it is reserving 16 bytes on the stack for just a single variable ?
Breakpoint 1, main () at test7.c:4
4 int x=10;
(gdb) disassemble main
Dump of assembler code for function main:
0x08048344 : lea 0x4(%esp),%ecx
0x08048348 : and $0xfffffff0,%esp
0x0804834b : pushl 0xfffffffc(%ecx)
0x0804834e : push %ebp
0x0804834f : mov %esp,%ebp
0x08048351 : push %ecx
0x08048352 : sub $0x10,%esp
0x08048355 : movl $0xa,0xfffffff8(%ebp)
0x0804835c : mov $0x0,%eax
0x08048361 : add $0x10,%esp
0x08048364 : pop %ecx
0x08048365 : pop %ebp
0x08048366 : lea 0xfffffffc(%ecx),%esp
0x08048369 : ret
End of assembler dump.
Moreover, when i try declaring upto 4 int variables, it still consumes 16 bytes, but as soon as i declare 5 variables, it takes 32 bytes on the stack. Is it some kind of optimization done by gcc ? My another doubt is when i declare char array of 100 bytes instead of the int variable, it takes 116 bytes on the stack. Why so ?
(gdb) list
1 #include
2
3 int main(int argc, char **argv) {
4 char buf[100];
5
6 return 0;
7 }
8
(gdb) disassemble main
Dump of assembler code for function main:
0x080483a4 : lea 0x4(%esp),%ecx
0x080483a8 : and $0xfffffff0,%esp
0x080483ab : pushl 0xfffffffc(%ecx)
0x080483ae : push %ebp
0x080483af : mov %esp,%ebp
0x080483b1 : push %ecx
0x080483b2 : sub $0x74,%esp
0x080483b5 : mov 0x4(%ecx),%eax
0x080483b8 : mov %eax,0xffffff88(%ebp)
0x080483bb : mov %gs:0x14,%eax
0x080483c1 : mov %eax,0xfffffff8(%ebp)
0x080483c4 : xor %eax,%eax
0x080483c6 : mov $0x0,%eax
0x080483cb : mov 0xfffffff8(%ebp),%edx
0x080483ce : xor %gs:0x14,%edx
0x080483d5 : je 0x80483dc
0x080483d7 : call 0x80482e4 <__stack_chk_fail@plt>
0x080483dc : add $0x74,%esp
0x080483df : pop %ecx
0x080483e0 : pop %ebp
0x080483e1 : lea 0xfffffffc(%ecx),%esp
0x080483e4 : ret
End of assembler dump.
Another doubt is what is being stored in ecx and pushed on the stack in the beginning of the disassembly and why it is ANDing esp with 0xfffffff0 ?
Kindly help. Replies would be appreciated.