Checkers:NPD.FUNC.CALL.MUST

From current

Reference > C/C++ checkers > NPD.FUNC.CALL.MUST

Possible null pointer may be dereferenced through a function call

Null is a special value in C/C++ that is used to indicate that a pointer doesn't point to any object. 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.FUNC.CALL.MUST checker flags situations in which a pointer value from a function call that might return null is subsequently 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

Code examples

Vulnerable code example

1  void reassign(int *argument, int *p) {
2    if (goodEnough(argument)) return;
3    *argument = *p;
4  }
5  
6  int *mymalloc() {
7    int *res = malloc(sizeof(int));
8    if (!res) return 0;
9    *res = 0;
10   return res;
11 }
12 
13 void npd_func_call_must(int *argument) {
14   int *p = mymalloc();
15   reassign(argument, p);
16 }

Depending on the result of the conditional statement at line 8, a null pointer may be passed to function npd_func_call_must, in which it might be dereferenced without being checked for a null value. This type of vulnerability can produce unexpected and unintended results.

Fixed code example

1  void reassign(int *argument, int *p) {
2    if (goodEnough(argument)) return;
3    *argument = *p;
4  }
5  
6  int *mymalloc() {
7    int *res = malloc(sizeof(int));
8    if (!res) return 0;
9    *res = 0;
10   return res;
11 }
12 
13 void npd_func_call_must(int *argument) {
14   int *p = mymalloc();
15   if (p!= 0) reassign(argument, p);
16 }

In the fixed code, *p is checked for null in line 15 before the dereference.

Related checkers

External guidance

Extension

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