How to test if an instance is corrupted?

2020-07-27 02:48发布

I found a bug in an existing program (c++ auto-generated code) in this method :

void _CallStyle _WFObjectVarAsStringExtractEFAgent::LoadValue(Pointer __VarAddress, aType theVarType) {
   absolute(tpPointer, VarAddress, __VarAddress);
   aLightObject Obj = nil;

   Obj = aLightObject(*VarAddress);

   if ( Obj == Nil ) {

      this->SetValue("");
   } else {
      this->SetValue(Obj->StringExtract(this->ExtractKind, this->ExtractParam, 0));
   }
   this->Lock();
   if ( Obj == Nil ) {
      this->Disable();
   } else {
      this->Enable();
   }
}

Sometime the line Obj = aLightObject(*VarAddress); returns not a valid aLightObject instance neither Nil (but an corrupted aLightObject instance).

So in the following line if ( Obj == Nil ) { we enter in the else bloc and the program fails when trying to execute the Obj->StringExtract call.

How can i test is the Obj instance is valid ?

标签: c++
1条回答
祖国的老花朵
2楼-- · 2020-07-27 02:58

If a pointer is not NULL/NIL/Nil or some other "recognisable 'isn't a pointer'" then it is almost imossible to determine if it's a valid pointer or not. Sure, if it's "nearly NULL", you can perhaps have a chance with some unportable code that checks something along the lines of:

 ptrdiff_t diff = NULL - reinterpret_cast<char *>(ptr);
 if (diff < -100000) cout << "Bad pointer" << ptr << endl;

You can also do a check if the object is a valid pointer and contains something that you know what it's supposed to be. The typical way to do that is to have a "magic", e.g.

 class myobject
 {
    public: 
       int magic;
    ...
       myobject() : magic(1234567)     // Make sure it's different for each type of object. 
       {
         ...
       }
     ....
 };

 ...
     if (obj->magic != 1234567)  cout << "Object is not right type..." << endl;

However, this DOES NOT WORK if obj is just some completely arbitrary value between 0...2n where n is the bitness of the machine. It will just crash as badly as if you didn't check it in the first place.

查看更多
登录 后发表回答