xcx0902's blog

By xcx0902, history, 8 months ago, In English

As we all know, we can write codes like this in C++:

int main() {
    int n;
    cin >> n;
    int a[n];
    ...
}

But when the inputed n is too large, this program will crash.

So,

  1. Why it would crash?
  2. What is the lowest value n to make it crash?
  3. Why using malloc will not cause this problem?
Tags vla
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
8 months ago, # |
  Vote: I like it +3 Vote: I do not like it

What do you think about memory allocated for such arrays? Is it allocated from the stack? If so, what would be if there is not enough memory? If memory is allocated by calling _alloca function, what if the function returned NULL pointer?

P.S. You could find answer in the standard.

»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

malloc allocate memory on the heap and if there is no space it's return a null pointer, other-ws if you declare an array like a[n] it is taken space in the stack of the program and if their is no space the program crash / stack-overflow it's a comman err happen also in recursive calls a lot.

»
8 months ago, # |
  Vote: I like it 0 Vote: I do not like it

As we all know, we can't write codes like this in C++, because the length expr must be constant, it's only (optionally) available in C. You could write VLAs in C++ because it's just one of GCC's non-portable extensions (and with the -pedantic compile command, you can't write VLAs in GCC either).

I hypothesize that the reason for the crash is similar to the reason for the crash caused by the declaration of a large array in a local function -- The VLAs as well as standard arrays are allocated on the Stack that is by default limited. Using std::malloc would not allocate memory on Stack, instead it's on Heap.

Anyway, now you are writing C++ code, consider using C++'s STL container std::vector, and avoid using VLAs.

See more pitfalls of VLA here.