1

I am trying to port some static checks from an old in-house C++ static checker to clang-tidy. Since I am really new to this tool, I am having a really hard time doing it and I am starting to think that it's not the proper tool to do what I want.

So basically what I am currently trying to implement, is a check on pointer initialization. I want to verify that a local pointer is properly initialized before being used.

For example if I take this sample of code:

void method(const char *);

int main(int argc, char **argv){
    const char * ptNotInit;

    const char * ptInit = "hello";

    method(ptNotInit);
    
    method(ptInit);

    return 0;
}

I want to get an error on method(ptNotInit) because I am passing a nullptr to method.

At first I try a very simple matcher:

Finder->addMatcher(varDecl(hasType(pointerType())).bind("pointerDeclaration"),this);
// and 
const auto *MatchedPtDecl = Result.Nodes.getNodeAs<VarDecl>("pointerDeclaration");
if ( MatchedPtDecl->hasInit() == false ) 
    // Do an error

So i get an error on ptNotInit and argv, so I add MatchedPtDecl->isLocalVarDecl() and all seems fine. Except that in my code sample I add:

ptNotInit = "Hello again";
method(ptNotInit);

I still get an error on ptNotInit when I abviously initialized it just before the call to method. I suppose that the VarDecl method hasInit() just apply for the declaration of the variable, explaining why it return false?

So my question is, how can I know when calling method(ptNotInit) if ptNotInit was initialized?

Clang-tidy seems powerful to find something, but I don't know how to find the lack of something, if you see what I mean... I try to write more complex matcher to find init like this one

Finder->addMatcher(binaryOperator(hasOperatorName("="),hasLHS(declRefExpr(hasType(pointerType()),hasDeclaration(varDecl().bind("pointerDeclaration"))).bind("affectation")))

If my pointer is on the left of an = operator, that should be an initialization... Ok why not, but at the end I want to know that there are no initialization, I don't want to match initialization syntax... Maybe I am taking the problem backward.

Any tips would help, or if you can point me to an already implemented checker doing something similar, that would be a great help!

Orienteer
  • 11
  • 1
  • 3
FLP
  • 11
  • 3

0 Answers0