6
int a;
cin >> a;
int ints[a];

Why does this not throw any kind of warning while compiling? How do I know when this array thing is actually using the heap or the stack?

g++ -std=c++11 -Wall *.cpp -o main

trincot
  • 317,000
  • 35
  • 244
  • 286
Farzher
  • 13,934
  • 21
  • 69
  • 100
  • 2
    *How do I know when this array thing is actually using the heap or the stack?* Simple, if you did not `new` (or `malloc`) then it is on the stack. – David Rodríguez - dribeas Jul 27 '13 at 15:45
  • Not true. What I'm doing right here is actually allocating memory in the heap without telling me. Because I'm using a variable size array that it has no idea the size of when building the stack. – Farzher Jul 27 '13 at 16:23
  • 2
    Well, that is one opinion, then again there is the documentation of your compiler that claims otherwise: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html, additionally take a look at the [documentation](http://man7.org/linux/man-pages/man3/alloca.3.html) of `alloca` that *also* allocates space at runtime in the stack. – David Rodríguez - dribeas Jul 28 '13 at 03:11
  • 1
    While I'm sure you're right in practice, to be pedantic, where does that GCC documentation say anything about the storage location of the resulting array? Sure, the storage *duration* is automatic, but that's orthogonal to the location. It'll presumably be on the stack in reality, but given that this is non-Standard behaviour, I don't think it's required to be. Then again, since people often get these concepts mixed up, the OP may or may not care about one or the other. :P – underscore_d Nov 21 '17 at 17:12

1 Answers1

10

ISO C++ disallows the use of variable length arrays, which g++ happily tells you if you increase the strictness of it by passing it the -pedantic flag.

Using -pedantic will issue a warning about things breaking the standard. If you want g++ to issue an error and with this refuse compilation because of such things; use -pedantic-errors.


g++ -Wall -pedantic -std=c++11 apa.cpp

apa.cpp: In function ‘int main(int, char**)’:
apa.cpp:8:13: warning: ISO C++ forbids variable length array ‘ints’ [-Wvla]
   int ints[a];
             ^
apa.cpp:8:7: warning: unused variable ‘ints’ [-Wunused-variable]
   int ints[a];
       ^
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196