0
 int m,n; cin>>m>>n; int A[m][n]; 

Question is: Will array A get memory on stack or heap in C++ ?

Edit: I know using new is a better route. This technique works in my mingw g++ compiler. I am just curious.

3
  • Technically it should be a compiler error. Commented Nov 17, 2015 at 16:47
  • But it works. So in that case ? Commented Nov 17, 2015 at 16:48
  • @DeepankarArya Doesn't work in Visual Studio, any version. Commented Nov 17, 2015 at 16:56

1 Answer 1

4

This behaviour depends on the particular compiler and is not part of the standard.

In gcc, which mingw is a port of, the memory for automatic variables as such, including variable lengths arrays is allocated on the stack.

According to the gcc manual:

6.19 Arrays of Variable Length

[...] These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits. [...] You can use the function alloca to get an effect much like variable-length arrays.

Ref: https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

According to man 3 alloca:

The space allocated by alloca() is allocated within the stack frame

Please keep in mind that:

ISO C++ forbids variable length arrays

Alternatively you can allocate your array dynamically (with new) or preferably use the C++ containers anyway where possible.


Edit: Added note on variable behaviour between compilers, based on Paul's comment.

Sign up to request clarification or add additional context in comments.

8 Comments

Works for me in mingw g++
@DeepankarArya "Works" because of a g++ extension. It is non-standard, and a year from now may not be supported.
Even in that case, where is the memory coming from stack or heap ?
I think you need "-pedantic" to get such a warning.
@FredLarson: Ok, without -Wall I get no warning at all
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.