Thursday, September 12, 2013

Is it safe to return a VLA?

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?

No comments:

Post a Comment