I have a scenario like this:
int main() {
int *p;
int *q;
bool cond1, cond2;
// Does some processing and sets the cond1 and cond2
if (cond1) {
p = // Assign valid address
q = NULL;
} else {
p = NULL;
q = // Assign valid address
}
// Does something else but cond1 and cond2 remains untouched
if (cond2) {
***// Using 'q' data members.***
}
}
There are only two condidtions in my code, cond1 and cond2. First if executes for cond1 and else executes for cond2.. Only one of them could be true at a time. I see coverity defect with bold/italic code. Coverity complains below message:
CID 25469 (#1 of 1): Explicit null dereferenced (FORWARD_NULL)
9. var_deref_op: Dereferencing null pointer q.
I do not understand why coverity complains here. In this scenario, by the time, I come in 'cond2', I already have 'q' set. Right? What is it that I did not understand?
Solutions I propose:
.. Would it be ok if I write !cond1 just like this:
if (!cond1) {
// Using 'q' data members.
}
.. Would it be ok if I add extra checks:
if (cond2 && q != NULL) {
// Using 'q' data members.
}
.. Is it false positive?
Anything else? Thank you in advance.