Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't int variable come before char array in terms of addressing no matter how I code it in C?

I'm reading Hacking: The Art of Exploitation (2nd Edition), and I'm currently on the section about buffer overflows.

In the first example, the variables are declared/initialized in this order:

int auth_flag = 0;
char password_buffer[16];

The example goes on to explain that you can use gdb to examine auth_flag and password_buffer's addresses, and you'll notice that auth_flag's address is higher than password_buffer's. Things to keep in mind: I'm running all of this in Ubuntu within Virtualbox on a Macbook Pro (Intel processor, 64-bit).

I compiled the first example's code like this: gcc -g -fno-stack-protector -o auth_overflow auth_overflow.c

As expected, auth_flag's address is higher than password_buffer's.

To remedy the problem presented above, the author explains you should switch the ordering of the declarations:

char password_buffer[16];
int auth_flag = 0;

I compiled the code the same way: gcc -g -fno-stack-protector -o auth_overflow2 auth_overflow2.c

Unfortunately, I did not see auth_flag's address being lower than password_buffer's. In fact, it was still higher. Why is this? What am I doing wrong?

like image 493
JoeB Avatar asked Aug 14 '10 03:08

JoeB


2 Answers

The compiler is allowed to choose whatever order it wants, in order to provide more optimal code, or even just random because it's easier to implement. One thing you might try is -O0 flag which disables all optimizations.

like image 190
Karl Bielefeldt Avatar answered Nov 19 '22 12:11

Karl Bielefeldt


Compilers are free to rearrange variables as they feel is best. I believe that the only restriction in the order of struct members. Those must be in memory in the same order as declared in the struct.

like image 45
Zan Lynx Avatar answered Nov 19 '22 12:11

Zan Lynx