Simple Trick to Detect Integer Overflow (C/C++)

It’s a compiler flag used to enable debug mode in gcc’s C++ Standard Library implementation. It turns some things that are Undefined Behaviour - out-of-bounds accesses in e.g. std::vector, etc - into guaranteed runtime-errors.

You can enable it in a couple of ways - if you’re compiling locally, use e.g.

g++ -std=c++14 my-solution.cpp -O3 -g3  -D_GLIBCXX_DEBUG

or by adding

#define _GLIBCXX_DEBUG

at the top of your cpp file, before any #includes.

For example, the following code has an out-of-bounds access, but actually runs “fine” on my laptop (i.e. it doesn’t crash):

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
   vector<pair<int, char>>  v;
   v.push_back ( { 6 , 'K' } ) ;
   v.push_back ( { 3 , 'T' } ) ;
   v.push_back ( { 6 , 'J' } ) ;
   sort ( v.begin() , v.end() ) ;

   for (const auto& pair : v)
   {
       cout << "(" << pair.first << " " << pair.second << ")";
   }
   cout << endl;

   cout << v[4].first << endl;  // Uh-oh - out-of-bounds access - almost certainly wrong!
}

Adding the #define at the top causes it to crash appropriately at runtime:

#define _GLIBCXX_DEBUG
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
   vector<pair<int, char>>  v;
   v.push_back ( { 6 , 'K' } ) ;
   v.push_back ( { 3 , 'T' } ) ;
   v.push_back ( { 6 , 'J' } ) ;
   sort ( v.begin() , v.end() ) ;

   for (const auto& pair : v)
   {
       cout << "(" << pair.first << " " << pair.second << ")";
   }
   cout << endl;

   cout << v[4].first << endl;  // Uh-oh - out-of-bounds access - almost certainly wrong!
}
/usr/include/c++/7/debug/vector:417:
Error: attempt to subscript container with out-of-bounds index 4, but 
container only holds 3 elements.

Objects involved in the operation:
    sequence "this" @ 0x0x7ffcb7929500 {
      type = std::__debug::vector<std::pair<int, char>, std::allocator<std::pair<int, char> > >;
    }
6 Likes