views:

117

answers:

3

I'm debugging an application and it segfaults at a position where it is almost impossible to determine which of the many instances causes the segfault.

I figured that if I'm able to resolve the position at which the object is created, I will know which instance is causing the problem and resolve the bug.

To be able to retrieve this information, gdb (or some other application) would of course have to override the default malloc/new/new[] implementations, but instrumenting my application with this would be alright.

One could argue that I could just put a breakpoint on the line before the one that segfaults and step into the object from there, but the problem is that this is a central message dispatcher loop which handles a lot of different messages and I'm not able to set a breakpoint condition in such a way as to trap my misbehaving object.

+3  A: 

So, at the point where the segfault occurs, you have the object, but you don't know which of many pieces of code that create such objects created it, right?

I'd instrument all of those object-creation bits and have them log the address of each object created to a file, along with the file and line number (the __LINE__ and __FILE__ pre-defined macros can help make this easy).

Then run the app under the debugger, let it trap the segfault and look the address of the offending object up in your log to find out where it was created. Then peel the next layer of the onion.

swillden
+1  A: 

Have you tried using a memory debugging library (e.g. dmalloc). Many of these already instrument new, etc. and records where an allocation is made. Some are easier to access from gdb than others though.

This product has a memory debugging feature that does what you want: http://www.allinea.com/index.php?page=48

atomice
Of the two answers given (as of now), this seems to me to be the best alternative. Thanks
Dr. Sbaitso
A: 

I would first try using the backtrace command in gdb when the segfault occurs. If that does not give me a good clue about what is going on, I would next try to use valgrind to check if there are any memory leaks occurring. These two steps are usually sufficient, in my experience, to narrow down and find the problem spot in most of the usual cases.

Regards.