NPD.FUNC.MUSTPossible null pointer is dereferencedAn 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.MUST checker flags situations in which a pointer value from a function call that might return null is subsequently dereferenced explicitly or passed to a function that dereferences it without checking it for null. Vulnerability and riskNull-pointer dereferences usually result in the failure of the process. These issues typically occur due to ineffective exception handling. Mitigation and preventionTo avoid this vulnerability:
Vulnerable code example1 int global; 2 3 int *xmalloc() { 4 if (global) return &global; 5 return 0; // xmalloc() may return NULL 6 } 7 8 void npd_func_must(int flag, char *arg) { 9 int *p = xmalloc(); // xmalloc() may return NULL 10 *p = 1; // pointer is dereferenced without validation 11 } Depending on the conditional statement at line 4, function xmalloc may pass a null pointer to npd_func_must, in which it's dereferenced. This type of vulnerability can produce unexpected and unintended results. Fixed code example1 int global; 2 3 int *xmalloc() { 4 if (global) return &global; 5 return 0; // xmalloc() may return NULL 6 } 7 8 void npd_func_must(int flag, char *arg) { 9 int *p = xmalloc(); // xmalloc() may return NULL 10 if (p!= 0) // check for null 11 *p = 1; // pointer is dereferenced 12 } In the fixed code, *p is checked for null at line 10 before the dereference. Related checkersExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |