NPD.CHECK.CALL.MIGHT

Previously checked null pointer may be dereferenced through a function call

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.CHECK.CALL.MIGHT checker flags situations in which a pointer that's been checked for a null value might subsequently be passed to a function that might dereference it without checking it for null.

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

Copy
  void reassign(int *argument, int *p) {
    if (goodEnough(argument)) return;
    *argument = *p;
  }
  
  void npd_check_call_might(int *argument) {
    int *p = getValue();
    if (p != 0) {
      *p = 1;
   }
   if (some_other_check()) return;
   reassign(argument, p);
 }

Although *p is checked for null at line 8, it may then be passed to function reassign, in which it can be dereferenced without being checked for null, depending on the result of the conditional statement at line 11. This type of vulnerability can produce unexpected and unintended results.

Fixed code example

Copy
  void reassign(int *argument, int *p) {
    if (goodEnough(argument)) return;
    *argument = *p;
  }
  
  void npd_check_call_might(int *argument) {
    int *p = getValue();
    if (p != 0) {
      *p = 1;
   }
   if (some_other_check()) return;
   if (p != 0) reassign(argument, p);
 }

In the fixed version of the code, a second check for null is placed in line 12.

Security training

Application security training materials provided by Secure Code Warrior.

Extension

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