Null-pointer constant value is dereferenced

An attempt to access data using a null pointer causes a runtime error. When a program dereferences a pointer that is expected to be valid but turns out to be null, a null pointer dereference occurs. Null-pointer dereference defects often occur due to ineffective error handling or race conditions, and typically cause abnormal program termination. Before a pointer is dereferenced in C/C++ code, it must be checked to confirm that it is not equal to null.

The NPD checkers look for instances in which a null or possibly null pointer is dereferenced. The NPD.CONST.DEREF checker flags situations in which a null-pointer constant value is dereferenced either explicitly or through a function call.

Vulnerability and risk

Null-pointer dereferences usually result in the failure of the process. These issues typically occur due to ineffective exception handling.

Mitigation and prevention

To avoid this vulnerability:

  • Check for a null value in the results of all functions that return values
  • Make sure all external inputs are validated
  • Explicitly initialize variables
  • Make sure that unusual exceptions are handled correctly

Vulnerable code example

1  void xstrcpy(char *dst, char *src) {
2    if (!src) return;
3    dst[0] = src[0];
4  }
6  void npd_const_deref(int flag, char *arg) {
7    xstrcpy(NULL, "Hello");
8  }

In this example, function xstrcpy may pass null pointer *dst to function npd_const_deref. This type of vulnerability can produce unexpected and unintended results.

Fixed code example

1  void xstrcpy(char *dst, char *src) {
2    if (!src) return;
3    if (!dst) return;
4    dst[0] = src[0];
5  }
7  void npd_const_deref(int flag, char *arg) {
8    xstrcpy(NULL, "Hello");
9  }

In the fixed code, *dst is checked for null at line 3.

Security training

Application security training materials provided by Secure Code Warrior.


This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.