[ACCEPTED]-What could cause a dynamic_cast to crash?-dynamic-cast

Accepted answer
Score: 41

Some possible reasons for the crash:

  • obj points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type).
  • obj points to an object that has been freed.
  • obj points to unmapped memory, or memory that has been mapped in such a way as to generate an exception when accessed (such as a guard page or inaccessible page).
  • obj points to an object with a polymorphic type, but that type was defined in an external library that was compiled with RTTI disabled.

Not 2 all of these problems necessarily cause 1 a crash in all situations.

Score: 11

I suggest using a different syntax for this 6 code snippet.

if (MonitorObjectH1C* monitorObject = dynamic_cast<MonitorObjectH1C*>(obj))
{
    axis = monitorObject->GetXaxis();
}

You can still crash if some 5 other thread is deleting what monitorObject 4 points to or if obj is crazy garbage, but 3 at least your problem isn't casting related 2 anymore and you're not doing the dynamic_cast 1 twice.

Score: 3

As it crashes only sometimes, i bet it's 2 a threading issue. Check all references 1 to 'obj':

grep -R 'obj.*=' .
Score: 2

dynamic_cast will return 0 if the cast fails 4 and you are casting to a pointer, which 3 is your case. The problem is that you have 2 either corrupted the heap earlier in your 1 code, or rtti wasn't enabled.

Score: 2

Are you sure that the value of 'obj' has 3 been correctly defined?

If for example it 2 is uninitialised (ie random) them I could 1 see it causing a crash.

Score: 1

Can the value of obj be changed by a different 1 thread?

More Related questions