Is it safe to return a VLA?

☆樱花仙子☆ 提交于 2019-12-24 01:08:22

问题


The following code uses the heap:

char* getResult(int length) {
    char* result = new char[length];
    // Fill result...
    return result;
}

int main(void) {
    char* result = getResult(100);
    // Do something...
    delete result;
}

So result has to be deleted somewhere, preferably by the owner.

The code below, from what I understand, use an extension called VLA, which is part of C99, and not part of the C++ standard (but supported by GCC, and other compilers):

char* getResult(int length) {
    char result[length];
    // Fill result...
    return result;
}

int main(void) {
    char* result = getResult(100);
    // Do something...
}

Am I correct in assuming that result is still allocated on the stack in this case?

Is result a copy, or is it a reference to garbage memory? Is the above code safe?


回答1:


Am I correct in assuming that result is still allocated on the stack in this case?

Correct. VLA have automatic storage duration.

Is result a copy, or is it a reference to garbage memory? Is the above code safe?

The code is not safe. The address returned by getResult is an invalid address. Dereferencing the pointer invokes undefined behavior.




回答2:


You can not return it, in C it will have automatic storage duration(the object will not be valid once you leave the scope) and returning it will invoke undefined behavior, from the C99 draft standard section 6.2.4 Storage durations of objects paragraph 6:

For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.27) If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.

In C++ we have to rely on the docs since it is extension in that case and the gcc docs on VLA says that it is deallocated when the scope ends:

These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.




回答3:


When you return from getResult(), the char array result will go out of scope and be deallocated along with the stack frame for the function call. If you want to preserve the function structure, you'll have to call malloc and later free the memory.



来源:https://stackoverflow.com/questions/18771165/is-it-safe-to-return-a-vla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!