Home > Blockchain >  How to warn not to use a variable after some point in g /clang ?
How to warn not to use a variable after some point in g /clang ?

Time:06-06

MyContainer a = ...;
a.myDeallocate();
a[0] = 3;       // This will crash

Given a C code snippet that looks like the above one, I would like to make the C compiler (either g or clang ) raise a warning saying that a must not be used after its deallocation, possibly by inserting a custom code:

MyContainer a = ...;
a.myDeallocate();
__should_not_use__(a); // If I put this code
a[0] = 3;              // The compiler will raise a warning at this point, hopefully.

Is there a way to do this?

CodePudding user response:

I don't think this is possible at compile-time, since the deallocation may be conditioned on some user input not known at compile-time.

A common practice is to use assert (assuming you have implemented operator[]) for random access to elements in your container:

#include <cassert>

class MyContainer {
    // ...
    Type operator[](int i) {
        assert (0 <= i && i < this->size());
        // ...
    }
};

Of course, you need to maintain the size of the container for this to work.

If out-of-bound indexing happens, this raises an AssertionError at runtime, but not at compile-time.

CodePudding user response:

I don't think there is a way to generate a warning or error for this sort of thing at compile-time; the best you could do is a run-time check (and then throw an exception or abort() the program if myDeallocate() had previously been called)

If possible, the preferred approach is to do the myDeallocate() code only in MyContainer's destructor. Then your code can look like this:

{
   MyContainer a = ...;
}  // deallocation happens implicitly here

a[0] = 3; // causes compile-time error; run-time bug avoided
  •  Tags:  
  • c
  • Related