Reputation: 449
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
Upvotes: 1
Views: 987
Reputation: 999
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.
Upvotes: 3