-4

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Truong Hua
  • 802
  • 6
  • 18

2 Answers2

3

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.

Matt
  • 13,674
  • 1
  • 18
  • 27
1
char tmp2[a];

where a is a non-constant integer, uses a C99 feature called variable length arrays, or VLAs.

That feature is not available in standard C++, although it's a language extension supported by the g++ compiler in non-conforming mode.

It's unspecified how memory is allocated for a VLA. It might be on the machine stack, like alloca, or it might be dynamically allocated memory.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331