Semmle 1.20
Skip to end of metadata
Go to start of metadata

Name: Returned pointer not checked

Description: Dereferencing an untested value from a function that can return null may lead to undefined behavior.

ID: cpp/missing-null-test

Kind: problem

Severity: recommendation

Query: MissingNullTest.ql
/**
 * @name Returned pointer not checked
 * @description Dereferencing an untested value from a function that can return null may lead to undefined behavior.
 * @kind problem
 * @id cpp/missing-null-test
 * @problem.severity recommendation
 * @tags reliability
 *       security
 *       external/cwe/cwe-476
 */
import cpp

from VariableAccess access
where maybeNull(access)
  and dereferenced(access)
select access, "Value may be null; it should be checked before dereferencing."

This query finds pointer dereferences that use a pointer returned from a function which may return NULL. Always check your pointers for NULL-ness before dereferencing them. Dereferencing a null pointer and attempting to modify its contents can lead to anything from a segmentation fault to corruption of important system data (for example, the interrupt table in some architectures).

Recommendation

Add a null check before dereferencing the pointer, or modify the function so that it always returns a non-null value.

Example

In this example, the function is not protected from dereferencing a null pointer. It should be updated to ensure that this cannot happen.

typedef struct {
	char name[100];
	int status;
} person;

void f() {
	person* buf = NULL;
	buf = malloc(sizeof(person));

	(*buf).status = 0; //access to buf before it was checked for NULL
}

References