Question

enter code hereI am seeing segfaults in a strange part of my code, and after using valgrind, it seemed the problem was the destructor of a parent being called during construction of the child. This is strange, so fired up gdb and indeed, I see constructor of child object being called, constructor of parent being called, and then destructor of parent being called before child constructor has exited. I did a fresh build, saw the same thing.

I assume this is impossible, and something funny is going on, but I have no idea what that might be or how to use gdb to determine what it is. Valgrind just tells me at a later point, when I try to use the parent object that I'm doing an invalid read because the relevant memory was deleted during construction of the child!

It's hard to break out the offending code to give a working example, but I can try to provide any other details that would be helpful. Using gcc 4.7.2.

* Edit * Here's a sketch of the inheritance chain:

class MKTimer: public MKSelfRegistrar<MKTimer>, public MKMakeable1<std::string>, public MKObject, public Timer;

MKObject is the offending parent.

MKTimer(const std::string& timer): Timer(timer) {}

MKObject() { some stuff here that doesn't seem relevant }

* Further Edit * I'll also mention that there are no explicit calls to delete and the gdb backtrace shows the call immediately above the parent destructor is the child constructor, so I don't think it's some other piece of code cleaning it up somehow.

Was it helpful?

Solution

There is only one reason for a child class constructor to call the destructor of its base class: failure.

So, your problem is likely due to an exception that is thrown somewhere in the construction of the child. This causes the stack to be unwound and all objects are destructed which have already been constructed. Since it is the constructor of the child class that calls the constructors of all its parents, it is also the constructor of the child that calls its destructor during exception cleanup.

However, don't give too much weight to the source code line that is produced by gdb, it may be wrong. So the bug may still be something wildly different.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top