简体   繁体   中英

Assembly: Too much stack space for local variables

I'm currently trying to understand some assembler code well enough to reconstruct the C code from it. While I'm nearly done with that, there is one thing about local variables that puzzles me.

Local variables are accessed by using the Base Pointer esp and substract their offsets, eg -0xc(%ebp) references a local variable. To interpret that into C code I need to know of which size these variables are (at least if they are arrays). One can do that by calculating the differences to the offsets of other variables. If there are the local variables -0xc(%ebp) and -0x8(%ebp) we know that -0xc(%ebp) is most likely 4 bytes long. But what about -0x8(%ebp) if there is no other access to any local variable in the disassebly? Can we suggest that it then must have a size of 8 bytes? I don't think so...

My problem is this: The compiler seems to set aside more space for local variables than is needed. Let me show you this simple example: An error function, disassembled with gdb.

push   %ebp              
mov    %esp,%ebp      
sub    $0x8,%esp               // 0x8 = 8 byte for local variables
mov    0x8(%ebp),%eax          // errormsg is a function argument  
mov    %eax,(%esp)             
call   0x80485cc <perror@plt>  // perror(errormsg)
movl   $0x1,(%esp)                 
call   0x804866c <exit@plt>    // exit(1)

This function obviously does not access any local variables, so we can suspect there are none. But still there are 8 bytes set aside for local variables, aren't there?

That's not the only example I've seen where there is space allocated for variables that isn't needed. I guess I overlook something but as long I do so it is impossible for my to find out about the sizes of all the variables which I need to write C code.

Any suggestions?

Thanks in advance!

The instruction mov %eax,(%esp) here is used in place of a push . So, whereas there aren't any local variables used, it's not like the reserved stack space is wasted. Granted, it looks like the function is reserving 8 bytes for local variables when it only needs to reserve 4, but perhaps that's the convention used by the compiler: always reserve stack in blocks of 8 bytes. It makes a certain amount of sense to keep the stack qword-aligned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM