Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

RNPD.DEREF

Suspicious dereference of pointer before null check

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 RNPD.DEREF checker finds instances in which a pointer is dereferenced before a null check. When there are no pointer changes on the trace between the dereference and the check, it is likely that the pointer is null at dereferencing, or the null check is improper.

Vulnerability and risk

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

A dereference before the null check can result in:

  • a runtime error if the pointer was null
  • unintended program results if a condition was written incorrectly
  • unnecessary code generated if there is a redundant check

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 rnpd_1(int* t, int v) {
2      *t = 0;  // t is dereferenced unconditionally
3      if (v < 0) v = -v;
4      if (t) *t = v;  // t is verified before dereference
5  }

In this example, the code dereferences 't' twice, once without any verification in line 2, and once guarded with a null check in line 4. Klocwork flags line 4, in which the null check occurs after the dereference. Of course, if the pointer is null, the application will crash after first dereference.

Related checkers