简体   繁体   中英

Scope of variably sized array

Is this always going to run as expected?

char *x;
if (...) {
    int len = dynamic_function();
    char x2[len];

    sprintf(x2, "hello %s", ...);

    x = x2;
}

printf("%s\n", x);
// prints hello


How does the compiler (GCC in my case) implement variably sized arrays, in each of C and C++?

No. x2 is local to the if statement's scope and you access it outside of it using a pointer. This results in undefined behaviour.

By the way, VLAs have been made optional in C11 and had never been part of C++. So it's better to avoid it.

The scope is explained here :

Jumping or breaking out of the scope of the array name deallocates the storage. Jumping into the scope is not allowed; you get an error message for it.

In your case the array is out of scope.

No, for two separate reasons:

C++: The code isn't valid C++. Arrays in C++ must have a compile-time constant size.

C: No, because the array only lives until the end of the block in which it was declared, and thus dereferencing x is undefined behaviour.

From C11, 6.2.4/2:

If an object is referred to outside of its lifetime, the behavior is undefined.

And 6.2.4/7 says that the variable-length array lives from its declaration until the end of its enclosing scope:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM