SEC-NULL-cmp-bef
In this section:
Synopsis
A pointer is compared with NULL, then dereferenced.
Enabled by default
Yes
Severity/Certainty
High/Low

Full description
A pointer is compared with NULL, then dereferenced. This might be caused by an accidental use of the wrong comparison operator, for example == instead of !=, or by accidentally swapping the then- and else- clauses of an if-statement. If the condition is evaluated and found to be true, the application will crash. Check comparison operators to make sure they test the correct condition, and make sure that branches have not been accidentally swapped.
Coding standards
- CERT EXP34-C
Do not dereference null pointers
- CWE 476
NULL Pointer Dereference
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
int example(void) {
int *p;
if (p == NULL) {
*p = 4; //dereference after comparison with NULL
}
return 1;
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
int example(void) {
int *p;
if (p != NULL) {
*p = 4; //OK - after comparison with non-NULL
}
return 1;
}