Posts Tagged ‘GCC’

Range Checked Vector Access

March 13, 2012 Leave a comment

By now, C programmers who’ve made the scary but necessary leap up to C++ should’ve gotten over their unfounded performance angst of using std::vector over raw arrays. If not, then “they” (I hate people like myself who use the term “they“) should consider one more reason for choosing std::vector over an “error prone” array when the need for a container of compact objects arises.

The reason is “range checked access during runtime“; and I don’t mean usingĀ  std::vector::at() all over your code. Stick with the more natural std::vector::operator[]() member function at each point of use, but use -D_GLIBCXX in the compiler command line of your “Debug” build configuration. (Of course, I’m talking about the GCC g++ compiler here, but I assume other compilers have a similar #define symbol that achieves the same effect.)

The figure below shows:

  1. A piece of code writing into the 11th element of a std::vector that is only 5 elements long (D’oh!).
  2. A portion of the compiler command line used to build the Release (left) and Debug (right) configurations.
  3. The console output after running the code.

In contrast, here’s what you get with a bad ole array:

The unsettling aspect about the three “D’oh” result cases (unlike the sole “no D’oh” case) is that the program didn’t crash spectacularly at the point of error. It kept humming along silently; camouflaging the location of the bug and insidiously propagating the error effect further downstream in the thread of execution. Bummer, I hate when that happens.

%d bloggers like this: