2

I'm involved in a C++ coding course and today I was discussing dynamic memory allocation with someone else in the course. He was recounting that in his previous C++ course (which was the first exposure to programming he had), they would build and use arrays using something like this:

#include <iostream>

int main(void) {
    int x;
    std::cin >> x;
    int arr[x];

    for (int i = 0; i < x; i++) {
        int k;
        std::cin >> k;
        arr[i] = k;
    }

    for (int i = 0; i < x; i++) {
        std::cout << "The value at arr[" << i << "] is " << arr[i] << std::endl;
    }

    return 0;
}

I compiled this without receiving any compilation errors using g++ and when I ran it (with small inputs for x) the output was exactly as expected. I changed the code to C and ran it using gcc and got the same result.

Why does this work? We don't know the array size at compile time, but we aren't dynamically allocating any memory and we still can read/write without error. My assumption is that the OS automatically allocates a certain amount of memory to the stack and we are just relying on the fact some of this memory hasn't been used yet, but I'm not totally satisfied. If it's safe, why do we use dynamic allocation for arrays of unknown size? If it isn't safe, why doesn't a compiler give me a warning (or is there a specific flag I need to add to see this warning)? Any insight into what is actually going on here would be greatly appreciated.

savram
  • 500
  • 4
  • 18
chemdog95
  • 366
  • 4
  • 16
  • 4
    VLAs are a compiler extension supported by GCC. – user0042 Oct 25 '17 at 15:21
  • What standard did you tell it to use? If you use something like `-std=c++14` it should not compile. It probably defaults to `-std=gnu-c++98` or something. – nwp Oct 25 '17 at 15:21
  • 2
    `int arr[x];` Is non-standard C++, if `x` is non-`constexpr`, but is, sometimes allowed by compiler extension. – Algirdas Preidžius Oct 25 '17 at 15:21
  • That's a variable length array (VLA). It's a non-standard g++ extension. Prefer to use `std::vector`. – R Sahu Oct 25 '17 at 15:21
  • clang supports this too: https://wandbox.org/permlink/wBSVQS9tz45qWAPN – Andriy Tylychko Oct 25 '17 at 15:24
  • It should be noted that while it is non-standard C++, it is covered by C99. g++ "simply" allows the C syntax. Somewhat counterintuitive, C11 made it optional again. https://en.wikipedia.org/wiki/Variable-length_array – cnettel Oct 25 '17 at 15:26

0 Answers0