I use shared_ptr with constructing an object like this:
std::tr1::shared_ptr<RawClusterBase> rawCluster(new RawClusterBase());
// ...
rawCluster->addLabel(p->userFriendlyTerms());
// ...
const TokenizedDocument * tokenizedDoc
= (TokenizedDocument *)documents.at(i);
const RawDocument * rawDoc
= dynamic_cast<const RawDocument *>(tokenizedDoc->getProperty(
TokenizedDocument::_PROPERTY_RAW_DOCUMENT));
rawCluster->addDocument(rawDoc);
I get a segmentation fault on the line with the dynamic_cast:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b92429 in __dynamic_cast () from /usr/lib/libstdc++.so.6
(gdb) backtrace
#0 0x00007ffff7b92429 in __dynamic_cast () from /usr/lib/libstdc++.so.6
#1 0x0000000000444aa5 in main (argc=1, argv=0x7fffffffe258) at clustering/document_test.cpp:271
Can anybody give me a pointer how to solve that? I have a other section in my project
where I use dynamic_cast to analyze subclass. I also plan to use the shared_ptr there
but I am afraid I would run into the same troubles. Is dynamic_cast not working with shared_ptr?
Any hint is greatly appreciated!
It’s hard to tell what might be going wrong. It could be due to a buffer overrun or access to a deallocated pointer, because such things are likely to overwrite a vtable pointer (which occurs at the beginning of an object). Try running the program in Valgrind.
Typically
dynamic_castshouldn’t crash. It returnsnullptr(or throwsstd::bad_castwhen using references) if the cast is invalid, or it fails to compile if the cast is totally impossible. But it doesn’t invoke UB, so I’d look elsewhere for the culprit.