找到你要的答案

Q:Where does variable length array/alloca allocate in stack

Q:可变长度的数组/分配不分配在栈

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.

我真的对alloca()功能因此好奇,我写了一个简单的测试程序如下:

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;
}

根据该文件,alloca()将在堆栈中分配内存。我运行使用gdb程序并指出(char *)&;TMP2 -(char *)= 44 -这意味着有44字节之间,距离之间的地址E-A,D-E,tmp3-d 4字节。我真的不理解编译器如何在堆栈中分配一个可变长度数组,希望有人能告诉我44个字节的含义是什么。

answer1: 回答1:

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.

alloca()不是标准的一部分。它被认为是编译器/机器相关的。因此,内联函数属于实现只。

说到这,如果我们谈论的x86机器,那么栈操作的专用堆栈指针SP /英语/ RSP登记使用(16 / 32 / 64位代码)包含地址的最后一个字/字/ qword推到堆栈。要保留更多的内存,我们只需要从SP寄存器中减去一些值。

因此,“典型”的配置(x)实现在x86是一个单CPU的指令:子SP,X.

answer2: 回答2:
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.

char tmp2[a];

其中一个是一个非整数常量,使用C99功能称为可变长度的数组,或乘坐。

在标准C++的功能是不可用的,虽然这是一个语言扩展隔离模式的G + +编译器支持。

这是未指定的内存是如何分配给一个数组。这可能是在机器堆栈,如分配,也可以动态分配的内存。

c  c99  variable-length-array