Search code examples
cc99variable-length-array

Where does variable length array/alloca allocate in stack


I am really curious about how alloca() function works and therefore, I have written a simple test program as follows:

int test() {
    int a = 0;
    int e;
    char tmp2[a]; //alloca
    int d;
    char* tmp3 = new char[2];
    tmp2[100] = 1;
    return 0;
}

int main(int argc, char** argv) {
    test();
    return 0;
}

According to the document, alloca() will allocate memory in stack. I run the program using gdb and figure out that (char*)&tmp2 - (char*)a = -44 which mean there are 44 bytes between them while the distances between the address of e-a, d-e, tmp3-d are 4 bytes. I really can not understand about how compiler can allocate a variable length array in stack and hope that someone can tell me what the meaning of the 44 bytes is.


Solution

  • alloca() is not a part of standard. It is considered to be compiler/machine dependent. Thus the intrinsics belong to implementation only.

    Having said this, if we talk about x86 machine, then stack manipulations are done by the use of dedicated stack pointer register - sp / esp / rsp (16/32/64 bits code) which contains address of last word/dword/qword pushed onto the stack. To reserve more memory we need just subtract some value from sp register.

    Thus "typical" alloca(x) implementation in x86 is just a single CPU instruction: sub sp, x.