Search code examples
arraysmemory-leaksclangdynamic-memory-allocation

C++ arrays with user input size (aka Why does this compile?)


I was experimenting with clang (10.0) on win 10, with the following snippet:

#include <iostream>

using namespace std;

int main()
{
  const int N = 10;

  int ii;
  cout << "Enter value for ii: ";
  cin >> ii;

  int a[N+ii];

  for (int i = 0; i < N+ii; ++i) {
    a[i] = 0;
  }

  for (int i = 0; i < N+ii; ++i) {
    cout << "a[ " << i << "] = " << a[i] << endl;
  }

  return 0;
}

I am not sure as to Why are there no compilation error (the size of the array a is unkown at compile time) ????

PS:

  1. Both for loops were meant to trigger segmentation fault.
  2. command to compile: clang.exe exp.cpp
  3. I have tried to run the code with large values for ii but it seems to work fine (ii = 10000, 100000, 1000000)

Solution

  • int a[N+ii];

    This is ill-formed in C++. The size of an array variable must be compile time constant.

    I am not sure as to Why are there no compilation error (the size of the array a is unkown at compile time) ????

    The C++ standard does not require that ill-formed programs could not be compiled. When a compiler intentionally compiles an ill-formed program, you are using a language extension.

    The standard does require that the language implementation issues a diagnostic message, informing the user of their ill-formed program. Clang doesn't conform to the standard unless you provide the -pedantic option when compiling. If you do use it, this is what clang says:

    warning: variable length arrays are a C99 feature [-Wvla-extension]
    

    And this is what clang document says about the option:

    -pedantic, --pedantic, -no-pedantic, --no-pedantic
    

    Warn on language extensions