问题
I've always wondered how I could get away with this:
int main(int argc, char **argv) {
printf("%p %s %d\n", &argv[1], argv[1], strlen(argv[1]));
char copy[strlen(argv[1]) + 1];
strcpy(copy, argv[1]);
printf("%p %s %d\n", ©, copy, strlen(copy));
return 0;
}
The char array copy
gets allocated anyway and the program runs fine, printing out the original and the copy. And Valgrind doesn’t complain about anything.
I thought dynamic arrays weren’t possible in C without malloc. Was I wrong?
回答1:
This is a C99 feature and could be implemented on prior versions by the compiler.
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. 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 brace-level is exited.
回答2:
Variable-length arrays originated as a GCC extension, but they were also adopted by C99.
They are still being allocated on the stack, so making them "huge" is considered bad style (and will likely break on you someday).
回答3:
Even before the existence of "variable length arrays," courtesy gcc and C99, there was:
alloca()
-- which allows dynamic allocation of stack ("automatic") memory.
回答4:
"Variable length arrays" were added to the C language in C99. This is covered in §6.7.5.2 "Array declarators":
If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime. Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.
来源:https://stackoverflow.com/questions/6656731/dynamic-arrays-in-c-without-malloc