0

Today a little argument erupted over the following code line in a fairly time critical piece of C++ that was running.

void func(std::string& str)
{
    ...
    uint8_t buffer[str.size() + 10];
    ...
}

Now obviously you can compile this in C as the standard supports dynamically sized arrays. However GCC C++ seems to allow this kind of construct through some kind of an extension. MSVC doesn't allow this kind of statement, so we were a bit puzzled.

  • Does GCC allocate it at declaration time and is this allocation done on the stack? Is it syntactic sugar for a dynamic allocation, like say using new to create an array?

  • Is there are performance penalty for using a dynamically sized array over say a static one, given that a static one would be allocated in the prologue?

The Welder
  • 916
  • 6
  • 24
  • "_Now obviously you can't compile this in C as it's a dynamically sized array._" As far as I know: this is wrong. VLAs are allowed in C, by a standard. They are not allowed in C++, but some compilers (like GCC) provide extensions, that allow such behavior (as far as I could guess: using the same methods as one implements in C). – Algirdas Preidžius Feb 03 '20 at 16:56
  • edit to change "obviously you can't" to "obviously you can" – M.M Feb 03 '20 at 23:18
  • https://stackoverflow.com/questions/58848183/dynamic-array-on-stack-vla-vs-heap-performance – M.M Feb 03 '20 at 23:23

0 Answers0