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.
Reasons which can cause a crash when using dynamic_cast
Verify if one of these cases is applicable to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With