Home > technical > Range Checked Vector Access

Range Checked Vector Access

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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: