A pointer is dereferenced where it is known to be NULL

tx0/c:null-dereferencedefaultwarningbug, cwe-476

What it finds

if (p == NULL && p->len > 0), if (!p || ...) turned around, or if (!p) { log(p->name); ... }: the pointer is dereferenced exactly where it has just been found to be NULL, which crashes. The condition was usually meant the other way.

Two shapes count: the right operand of && after a test for NULL, or of || after a test for not NULL; and the first statement of the body of an if that tests for NULL that mentions the pointer, if the statements before it call only functions of the C library and the statement does not assign the pointer. The pointer must be a local variable or parameter.

From the rule's source, null_dereference.rs.

Example from the rule's tests
#include <stddef.h>#include <stdio.h> struct s { int len; const char *name; }; int check(struct s *p, struct s *q){  if (p == NULL && p->len > 0)tx0 reports: p is dereferenced where it is NULL    return 1;  if (q || q->len)tx0 reports: q is dereferenced where it is NULL    return 2;  if (!p) {    printf("%s\n", p->name);tx0 reports: p is dereferenced where it is NULL    return 3;  }  if (p != NULL && p->len > 0)    return 4;  if (!q) {    q = p;    return q->len;  }  return 0;}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/c:null-dereference" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:null-dereference] reason="..."

tx0 explain tx0/c:null-dereference shows the same in the terminal. Found a false positive? Report it.