Hi all,
I'm getting a SIGSEGV when using dynamic_cast. It's a very simple
executable(code below) that is built using the standalone toolchain and
ran on a Pandaboard with Linaro Android 4.0.3.
According to the documentation the standalone toolchain has exceptions
and rtti enabled by default so I don't use the specific flags. I link against the
shared version of the "gnustl" library and also with "supc++". If I check my
executable with "nm" the dynamic_cast symbol is indeed undefined explaining
the crash.
What am I doing wrong here? Do I need to use some other compiler or linker flags?
Thanks
Compiler flags:
-marm -march=armv7-a -mfloat-abi=softfp -mfpu=neon -Wuninitialized -Wno-psabi -fsigned-char -w -DANDROID -fPIC -g -Wstrict-aliasing=3 -Wstrict-overflow=3 -D_DEBUG
Linker flags:
-Wl,-nostdlib -Wl,-lgnustl_shared -Wl,-lsupc++ -rdynamic -ldl -lgcc -lc -lm -ldl
Code(corrected example from
cppreference.com):
#include <iostream>
#include <typeinfo>
struct V
{
virtual void f() {}; // must be polymorphic to use runtime-checked dynamic_cast
};
struct A : virtual V {};
struct B : virtual V
{
B(V* v, A* a)
{
// casts during construction
dynamic_cast<B*>(v); // well-defined: v of type V*, V base of B, results in B*
dynamic_cast<B*>(a); // undefined behavior: a has type A*, A not a base of B
}
};
struct D : A, B
{
D() : B((A*)this, this) { }
};
struct Base
{
virtual ~Base() {}
};
struct Derived : Base
{
virtual void name() {}
};
struct Some
{
virtual ~Some() {}
};
int main()
{
D d; // the most derived object
A& a = d; // upcast,dynamic_cast may be used, but unnecessary
try
{
D& new_d = dynamic_cast<D&>(a); // downcast
B& new_b = dynamic_cast<B&>(a); // sidecast
}
catch (const std::bad_cast& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
Base* b1 = new Base;
if(Derived* d = dynamic_cast<Derived*>(b1))
{
std::cout << "downcast from b1 to d successful\n";
d->name(); // safe to call
}
Base* b2 = new Derived;
if(Derived* d = dynamic_cast<Derived*>(b2))
{
std::cout <<"downcast from b2 to d successful\n";
d->name(); // safe to call
}
if(Some* d = dynamic_cast<Some*>(b1))
{
std::cout << "downcast from b1 to Some successful\n";
}
delete b1;
delete b2;
}