1

I'm playing with clang static analyzer ( clang++ --analyze or clang-tidy, win64, v6.0.1).

Clang analyzer can detect a null dereference in this case:

class SomeClass {
    public:
    int a = 5;
};

int GetA( SomeClass* someClass ) {
    return someClass->a;
}
int main() {
    SomeClass* someClass = nullptr;
    return GetA( someClass );
}

but not this one:

class SomeClass {
    public:
    int a = 5;
};

int GetA( SomeClass* someClass ) {
    return someClass->a;
}
SomeClass* someClass = nullptr;
int main() {
    return GetA( someClass );
}

I am new to clang-tidy, am i missing something?

Regards

benoitj
  • 419
  • 3
  • 13

1 Answers1

3

I can give you the answer from a viewpoint of a developer of the PVS-Studio analyzer. The PVS-Studio analyzer similarly detects the error in the first case and will be quiet in the second case. By making the variable global, you considerably increase the difficulty of detecting errors, related to the use of this variable. Global variable can change at any place and it's very difficult to track when and under what conditions this can happen. Very often it's better even not to try.

For example, you can initialize a variable in the following way.

SomeClass* someClass = nullptr;

class Init
{
public:
  SomeClass m_c;
  Init() { someClass = &m_c; }
} foo;

I'm not saying, that this is the right way of variable initialization. I just want to show to what extent everything is not obvious.

Anyway, this is another reason not to use global variables. Global variables are the scourge.

AndreyKarpov
  • 1,083
  • 6
  • 17
  • Thanks! I perfectly understand that the pointer can be set anywhere, i just assumed/hopped a static analyzer would have a more "defensive" attitude towards the GetA func, enforcing devs to assert or test the pointer – benoitj Aug 16 '18 at 16:47
  • @benoitj I think Andrey's answer is the best you're going to get to this question; the fundamental issues are the same for Clang SA as for PVS-Studio. I explained some of them when answering [Why are static analysis tools missing this seemingly obvious case?](https://stackoverflow.com/a/57846117/2659307). Here there is the additional challenge of accurately tracking global variables, making it even more difficult. – Scott McPeak Sep 08 '19 at 23:39