Is it possible to have g++ show an error when compiling the following file with some flag?
#include <iostream>
using namespace std;
int main()
{
int arr[ 2 ];
cout << arr[ 4 ] << endl;
return 0;
}
I saw some things like gcc -Wall -O2 main.c
which only works with C, not C++.
For raw arrays, I don't think so, because
-fbounds-check
didn't work with your example and MingW g++ 4.4.1, and because the old 3.x docs I have sayHowever, with
std::vector
you can useat
to have a slightly impractical run-time bounds-checking (generates exception). And you can use a special debug version of the standard library, that provides practical run-time bounds-checking for[]
. For example, when compiling…… you get different respectively non-checking and checking behavior for the release and debug versions of the g++ standard library implementation:
Reportedly for newer g++ versions (after 4.0) you don't need the
_GLIBCXX_DEBUG_PEDANTIC
symbol. For details, see the GNU documentation.Cheers & hth.,
I recall seeing a gcc or g++ warning message from ffmpeg or x264 along the lines of
"warning index of array may be out of bounds"
http://gcc.gnu.org/ml/gcc/2000-07/msg01000.html
seems like it probably made it in.
The constraint is that you have an example like yours above. as soon as you have have variables instead of literals it is not possible. except perhaps in a simple loop.
Not at compile time. You might be able to check that at runtime though.
For that take a look at: Runtime array bounds checking with g++
You can replace arrays with
std::vector
. Vector has accessor member function (std::vector::at
) that does bounds checking at runtime.Compile time check for buffer overflow is a very hard undecidable problem, unfortunately. It's usually handled by a full blown static analysis tool.
You can use a static analyser such as Cppcheck. When run on your above code:
You can integrate Cppcheck into your build procedure and consider your code built successfully only if Cppcheck passes.