Search code examples
c++cgccdynamic-arrays

Is it safe to return a VLA?


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?


Solution

  • 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.