In general, there is a code. The variable is passed to the need_size variable. Next, create a string of size need_size. And then the snag. As far as I know, according to the C standard, the size of static arrays should be known at the compilation stage. However, gcc versions 3 and 4 compile this miracle without complaints (even without Vorning), visual c - immediately throws three errors, one of them is the expected constant expression, which looks logical. The code compiled by gcc is working correctly. Tell me, does gcc replace this code with a malloc call? Or is it the magic of Hogwarts and nothing stands out and with this use there is a risk to go beyond memory?

char* string_space(char *str, int need_size) { char stringspace[need_size]; ... } 
  • 2
    @Bogdan Bessonov, you have already been answered, so the remark is only on the question. The term "static array" is somewhat confusing, since for static arrays even gcc does not allow variables in the length description - only for automatic. - alexlz
  • A static array in my understanding is an array, the memory for which is allocated statically at the compilation stage. Thanks for the comment - b2soft
  • one
    Well, here the memory for which is allocated statically at the compilation stage is also moments. It's one thing automatic, for which memory in languages ​​with a block structure, as Grandpa Dijkstra found, can be allocated (and allocated) in a stack, and the only thing that prevents arrays with variable boundaries is calculating the offset in the frames of this stack, and the other is static when memory is allocated at the compilation and linking stage, and a different array size means rebuilding the executable file. - alexlz

1 answer 1

Yes, this is a non-standard GCC extension.

Link to documentation: https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Variable-Length.html#Variable-Length

Memory is allocated on the stack using alloca . And yes, if you require too much memory, you can get a stack overflow.


Addition: if we are talking about pure C, automatic arrays of variable length are part of the language, starting with the standard C99. MSVC, however, includes support for new C standards extremely slowly. Moreover, they have excellent support for C ++ standards. (The C ++ standard does not include variable-length arrays, so C ++ is no longer a superset of C.)

  • @ Bogdan Bessonov: added the answer. - VladD
  • I know about crosses. In general, this is part of the laboratory at the university of one of my friends, C is taught there in the framework of C89. However, as I was taught. That's why I'm looking at what this nonsense is) - b2soft