2

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?

Dark Eagle
  • 107
  • 3
  • 10
  • are you certain your program changed when you recompiled? sometimes with changes that don't affect the functionality of the program, the change can get "optimized" out by the compiler. – phormalitize Jun 16 '16 at 17:21
  • 1
    Possible duplicate of [Order of local variable allocation on the stack](http://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack). – Mark Plotnick Jun 16 '16 at 18:27

1 Answers1

7

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.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • 2
    You are correct: the C standard says literally nothing about any stack. The word does not appear anywhere in the standard. The same with "heap". – John Bollinger Jun 16 '16 at 17:42
  • Because stack/stack size, is compiler and OS specific. I'm telling this, because I saw people saying that stack size in Java is bigger then in C :)) – Michi Jun 16 '16 at 19:34
  • 1
    "the variables can be wherever". This can often be observed for local variables in optimized code. They are not allocated on stack at all (registers only). – dbrank0 Jun 17 '16 at 07:08