Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What g++ flags will make a runtime-sized array on stack cause compiler error?

Tags:

c++

arrays

g++

Creating a array on the stack with the size determined at runtime is allowed by default with g++:

int size;
cout << "Enter array size: " 
cin >> size;
MyObject stack_array[size];

According answers of this question, it's a bad idea and I agree. Apparently I should be able to use a g++ flag to enforce strict/standard C++ and get a compiler error. The code still compiles even with the following flags:

g++ -ansi -pedantic -Wall -Wextra -Werror -std=c++0x

How can I prevent this code from compiling?

Here is my version info:

g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/lto-wrapper
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.5.2-8ubuntu4' --with-bugurl=file:///usr/share/doc/gcc-4.5/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.5 --enable-shared --enable-multiarch --with-multiarch-defaults=i386-linux-gnu --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib/i386-linux-gnu --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.5 --libdir=/usr/lib/i386-linux-gnu --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-plugin --enable-gold --enable-ld=default --with-plugin-ld=ld.gold --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread model: posix
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4) 
like image 235
Pete Avatar asked Dec 03 '11 20:12

Pete


2 Answers

Upgrade your compiler (it needs to support -Wvla flag, you can hunt for it in the changelogs or just upgrade to 4.6.2). 4.6 will correctly reject it:

> g++ -std=c++0x -Wall -Werror -pedantic -o vla.exe vla.cpp
vla.cpp: In function 'int main()':
vla.cpp:3:19: error: ISO C++ forbids variable length array 'array' [-Werror=vla]
vla.cpp:3:9: error: unused variable 'array' [-Werror=unused-variable]
cc1plus.exe: all warnings being treated as errors

Also, -ansi is the same as -std=c++98, so don't use that flag if you want C++11.

like image 134
Cat Plus Plus Avatar answered Sep 28 '22 08:09

Cat Plus Plus


On my computer (Arch Linux, GCC 4.6.2) using g++ -pedantic file.cpp returns

test.cpp: In function ‘int main()’:
test.cpp:7:12: warning: ISO C++ forbids variable length array ‘arry’ [-Wvla]
like image 22
Hauleth Avatar answered Sep 28 '22 08:09

Hauleth