What could cause a dynamic_cast to crash?

前端 未结 6 1068
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 16:58

I have a piece of code looking like this :

TAxis *axis = 0;
if (dynamic_cast(obj))
   axis = (dynamic_cast         


        
相关标签:
6条回答
  • 2020-12-06 17:10

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

    grep -R 'obj.*=' .
    0 讨论(0)
  • 2020-12-06 17:15

    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 all of these problems necessarily cause a crash in all situations.

    0 讨论(0)
  • 2020-12-06 17:15

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

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

    0 讨论(0)
  • 2020-12-06 17:21

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

    0 讨论(0)
  • 2020-12-06 17:35

    I suggest using a different syntax for this code snippet.

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

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

    0 讨论(0)
  • 2020-12-06 17:35

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

    0 讨论(0)
提交回复
热议问题