RNPD.CALL

Suspicious dereference of pointer in function call 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.CALL checker finds instances in which a pointer is dereferenced by an argument being passed to a function 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 dereferenced before the null check.

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 deref(int *p){
2         *p = *p + 10;
3   }
4  
5   void rnpd_2(int *t){
6  
7         deref(t);
8         if (!t) return;
9     *t ++;
10  }

In this example, the code dereferences 't' twice, once without any verification through the call to function deref(), and once guarded with a null check. Klocwork flags line 8, in which the null check occurs after the dereference in line 7. Of course, if the pointer is null, the application will crash after first dereference.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.