C++: dynamic_cast causes a SEGFAULT even when the object that is casted is not NULL. How can that happen?

StackOverflow https://stackoverflow.com/questions/14243854

Question

Suppose I have a class A and a class B that is derived from A. Now, I want to cast a const A* (called "a") to a B* using dynamic_cast (see below). If "a" really was a B*, then my resulting object pointer should be fine. If "a" was not a B*, then I will get NULL.

const A* a = new B();
const B* b = dynamic_cast<const B*>(a);

For some reason, the dynamic_cast operation causes a SEGFAULT. How can that happen if "a" is NOT NULL? I guess that dynamic_cast will give me a NULL pointer if there were any conversion problems, instead of a SEGFAULT. I should only get a SEGFAULT if I am trying to access "b" and the dynamic cast was unsuccessful, right? I have not even tried to access "b" yet.

So, how can this happen? Is there anything that can cause dynamic_cast to SEGFAULT in the above code, that I am not aware of?

Thanks in advance :-)

EDIT: Running my actual program through GDB gives this output:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) where
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff6c0e612 in __cxxabiv1::__dynamic_cast (src_ptr=<optimized out>, 
src_type=0x4fa6b0, dst_type=0x516bb0, src2dst=0)
at /var/tmp/portage/sys-devel/gcc-4.6.3/work/gcc-4.6.3/libstdc++-v3/libsupc++/dyncast.cc:61

The next line in the output just points to the line in my code where I do the dynamic casting.

Was it helpful?

Solution

Reasons which can cause a crash when using dynamic_cast

  • pointer points to a free memory block.
  • pointer points to a non-polymorphic type.
  • pointer points to an object with a polymorphic type but present in an external library compiled with RTTI disabled.
  • pointer points to a memory accessing which can cause protection exception (such as a guard page or inaccessible page).

Verify if one of these cases is applicable to you.

OTHER TIPS

For anyone else like me, you may have accidentally given the cast object the same variable name as the object you were casting it from!

A *name = new B();
B *name = dynamic_cast<B*>(name);

This is clearly wrong with such obvious code however out in the wild mistakes like this can be much harder to spot as variables are dispersed and casts are obfuscated!

I got this one once... it was because I'd failed to initialise the pointer, and it was pointing at random garbage.

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