Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object throwing std::out_of_range

A program of mine throws a std::out_of_range. I know the reason for that, I'm accessing a vector with index -1 somewhere. What I don't know is the name of the vector (variable name) and location in the code. The error message produced by my program looks like this:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check
zsh: abort (core dumped)  ./main.x config.cfg  

whereas the error message produced by the code of some other guy (he uses g++ too) and posted in the question C++ accessing vector looks like this:

Error for vec.at(i).setVec(tmp);
Error is:  terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check  

I.e. he is told the name of the variable. My question is:

Is there any way to tell g++/gcc to give me the extended info? Maybe even include line numbers (don't know whether that's possible but hey, a guy can dream ;) ).
Just for funsies I ran my program in gdb with the catch thrown option (I might add, I have near zero experience in using an actual debugger) which didn't tell me anything new either, in fact, it didn't tell me that the error was due to a std::out_of_range exception.

Btw, my compiler flags (for debug) are:

CFLAGS = --exceptions -I$(ROOTSYS)/include --std=c++11 -Wall -g -O0 -fno-inline -fno-eliminate-unused-debug-types
like image 882
elemakil Avatar asked Feb 05 '13 11:02

elemakil


2 Answers

After hitting the breakpoint enter bt (backtrace) command in the gdb shell. This will print the stack trace (a sequence of function calls leading to the error).

To get the variable name you can now use up command to navigate upwards in the stack and see what variables where used in each of those functions.

like image 90
Basilevs Avatar answered Nov 11 '22 01:11

Basilevs


Put a breakpoint on std::out_of_range::out_of_range. An exception object, like all C++ objects, starts its life after its constructor exits.

[EDIT] Comment made it clear: the problem the string produced by std::out_of_range::what(). That's implementation-defined. Obviously in your case it's composed from __FUNCTION__, a GCC macro which names the current (i.e. throwing) function. But such a function only knows this, i.e. the pointer to the current object and not its name. In the other case, the objects name is retrieved via some other method, not std::out_of_range::what().

like image 31
MSalters Avatar answered Nov 11 '22 02:11

MSalters