Search code examples
cassemblygccgdbstack-frame

How memory is allocated for a static array on the stack?


I started a deep study of exploits, working with memory, etc., and ran into the same problem. Everywhere it is written that memory is allocated to variables in the order of their declaration inside the function, but in my case it has absolutely no effect on this, i.e. the pointer to the first element of the array in any of the options remains in one place. Here is an example: I have a code in C

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void myFunction() {
        char x[20];
        int a =1;
        int b= 2;
        int c = 3;
        int d = 4;
    }
    int main(int argc, char *argv[]) {
        myFunction();
    }

I compile it and debug it, and output the value of the address of the array x:enter image description here Then I edit the code and declare the array after initializing the d variable:

  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  void myFunction() {
     int a =1;`your text`
     int b= 2;
     int c = 3;
     int d = 4;
     char x[20];
  }
  int main(int argc, char *argv[]) {
     myFunction();
  }

And I do the same operations as in the previous case:enter image description here

As you can see, the position of the array on the stack has not changed in any way, can you please explain to me why this is happening?


Solution

  • How memory is allocated for a static array on the stack?

    None of the objects defined in your program are static. They all have automatic storage duration, not static. Static objects are not stored on the stack.

    Everywhere it is written that memory is allocated to variables in the order of their declaration inside the function,…

    This is not written everywhere, and it is not true generally. Any source that says that is wrong. It might be partially true in some limited circumstances, such as compiling without optimization, but it is not true generally.

    As you can see, the position of the array on the stack has not changed in any way, can you please explain to me why this is happening?

    Compilers commonly group objects by their alignment requirements (among other factors), to reduce the total amount of space needed for them. In this case, the compiler has put all of the int objects, which likely have a four-byte alignment requirement, first1, and has put the char array, which has a one-byte alignment requirement, after them. That choice of location remained the same regardless of the order in which the definitions appear.

    Footnote

    1 This does not mean first in chronological order. In this case, the compiler seems to be organizing more-strictly-aligned objects at lower addresses, hence first in address order, not first in the direction the stack is grown. Other design choices could be made, such as putting the more strictly aligned objects at higher addresses.