简体   繁体   中英

How are variables stored in the stack

Since I know that the stack is a FILO segment (First In Last Out,) when creating this program (shown below,) I think the auth_flag vairable is stored after the password_buffer variable:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_authentication(char *password) {
int auth_flag = 0;
char password_buffer[16];   
...
}

int main(int argc, char *argv[]) {
....
}

When I check the places of auth_flag and password_buffer in gdb, I indeed see that auth_flag is after password_buffer by 28 bytes:

(gdb) x/s password_buffer
0x7fffffffe3f0: "\001"
(gdb) x/xw &auth_flag
0x7fffffffe40c: 0x00000000
(gdb) # now let's print how many bytes is auth_flag away from      password_buffer
(gdb) print 0x7fffffffe40c - 0x7fffffffe3f0
$3 = 28
(gdb) # so auth_flag is 28 bytes after password_buffer

After reversing the variables' declaration, I expect to have password_buffer stored after auth_flag:

int check_authentication(char *password) {
char password_buffer[16];
int auth_flag = 0;    
...
}

However, this is not what happens, since experimenting with gdb produced the same results. How is this possible? Shouldn't auth_flag be before password_buffer?

Even though the variables are (usually) put to the stack then the function is run the compiler is free to put them there in any order it wants. There is usually no reason for the developer to care about the order whereas the compiler knows better in which order they should be to be optimal.

If you care about order you can use a struct and the compiler won't reorder those.

Also If I remember correctly the C standard doesn't even require a stack to exist, the variables can be wherever.

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