gcc memory allocation issue - buffer overflow attack
c, gcc
Solution
Yes, if run with the `-fstack-protector` flag.
When run with the flag, GCC adds stack canaries, sorts array variables to the highest part of the stack frame to make it more difficult to overflow them and corrupt other variables, and makes copies of the function arguments to be stored with the other locals.
See the Wikipedia page on Buffer overflow protection and the ProPolice homepage for more information
Problem
Does gcc do memory allocation intelligently to prevent buffer overflow attack? ``` int function(char *str) { int a = 0; // See the char b[16] = "abcd"; // changes here if(!strcmp(b, str)) a = 1; return a; } ``` and ``` int function(char *str) { char b[16] = "abcd"; // See the int a = 0; // changes here if(!strcmp(b, str)) a = 1; return a; } ``` When I debug it with gdb, it always allocate memory first to integer variables and then character array; no matter what is the order of variable declaration. i.e. In above both cases, compiler allocates memory first to `a` and then to `b`. ``` (higher address) Memory | | | | +--------+ | | | | | | | | +--------+ <----- b (16 bytes) | | +--------+ <----- a (4 bytes) | | (lower address) ``` So, even if we supply more than 16 character in `str`, it can not affect value of `a`. Can anybody help me out here? Thank you.