Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gdb not catching std::out_of_range thrown by vector

Tags:

c++

mingw

gdb

Compiling the following with MinGW 4.6.2 (with g++ -g -std=c++0x), gdb doesn't seem to want catch the std::out_of_range if I try catch throw. if I throw it manually it catches fine, am I doing something wrong?

#include <stdexcept>
#include <vector>

int main()
{
    std::vector<char> vec(10);
    try {       
        vec.at(10); // this won't be caught by gdb

        // throw std::out_of_range(""); // this will
    }
    catch (std::out_of_range const& e) {        
    }   
}
like image 381
user657267 Avatar asked Apr 23 '12 07:04

user657267


3 Answers

You are not actually catching exception in gdb. Try catch catch to catch exception.

like image 151
ks1322 Avatar answered Oct 19 '22 07:10

ks1322


Add a breakpoint where std::vector throws the exception. At this moment, no stack unwinding has occured yet so you should be able to fully backtrace to the original statement.

I was able to achieve this, but only in a very implementation-defined way:

1) Locate the vector's range checking function in stl_vector.h:

_M_range_check(size_type __n) const
{
    if (__n >= this->size())
          __throw_out_of_range(__N("vector::_M_range_check"));
}

2) Add a breakpoint to the line where __throw_out_of_range() is called. Note: I tried adding a breakpoint by 'break __throw_out_of_range' but this did not work. Instead, I need to hardcode the breakpoint with it's file and line number (break stl_vector.h:794). You can add this to your .gdbinit file to have gdb break on all failed range checks.

like image 4
roffez Avatar answered Nov 06 '22 20:11

roffez


As you've seeen, the exception from std::vector::at() is thrown by __throw_out_of_range which is a function inside libstdc++.so, so I suspect there's some problem on Mingw that prevents GDB from setting a catchpoint in a shared library. Or maybe your libstdc++ wasn't built with -g.

If your GCC was configured with --enable-libstdcxx-debug you would have a second set of libs built with -O0 -g that might work better when debugging, but that option isn't used often.

like image 3
Jonathan Wakely Avatar answered Nov 06 '22 19:11

Jonathan Wakely