Search code examples
c++qtqt5qsharedpointermarble

Seg Fault when using QSharedPointers in qt5


I'm using qt5.5.1 with qt-creator 3.5.1 and am trying to set a style on a GeoDataPlacemark with a GeoDataStyle. It used to work fine, but after the Marble update to use shared pointers instead of direct pointers, my program seg faults. Using GDB, I've traced the seg fault to the line where I create a QSharedPointer with the styleArch direct pointer. Does anyone have an idea what could be the issue?

My old code was as follows:

styleArch->setIconStyle( *icon );
place->setStyle( styleArch ); //Old Marble

The new code, which uses the new Marble API is as follows:

styleArch->setIconStyle( *icon );
place->setStyle(Marble::GeoDataStyle::Ptr( styleArch )); //New Marble

Thanks for your time!


Solution

  • The line: Marble::GeoDataStyle::Ptr( styleArch ) creates a temporary QSharedPointer and passes it styleArch as a pointer. QSharedPointer takes ownership of styleArch* at this point which means that whatever previously owned styleArch* no longer has it.

    The setStyle method takes a const reference to the temporary QSharedPointer you just created and uses it briefly, but importantly, does not increment the QSharedPointer's reference counter (because it is const).

    This means that as soon as the call to setStyle completes, the temporary QSharedPointer goes out of scope (calls its destructor) and deletes the styleArch object from the heap. This leaves you in a bad way because the original owner of styleArch* has no idea it's now holding an invalid pointer. Any further use of styleArch* should segfault.

    The easiest fix would be to update styleArch*'s owner to hold a QSharedPointer<> to style arch instead.