NPD.FUNC.MIGHTPossible null pointer may be 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.MIGHT checker flags situations in which a pointer value from a function call that might return null might subsequently be 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 void xstrcpy(char *dst, char *src){ 2 if (!src) return; 3 dst[0] = src[0]; 4 } 5 6 char global; 7 8 char *xmalloc() { 9 if (global) return &global; 10 return 0; 11 } 12 13 void npd_func_might(int flag, char *arg) { 14 char *p = &arg; 15 if (flag) p = xmalloc(); // xmalloc() may return NULL 16 if (arg) { p = arg; } // p may get a new value here 17 xstrcpy(p, "Hello"); // p will be dereferenced in xstrcpy() 18 } Depending on the conditional statement at line 9, function xmalloc may pass a null pointer to function npd_func_might and then xstrcpy, in which it's dereferenced, depending on the condition at line 16. This type of vulnerability can produce unexpected and unintended results. Fixed code example1 void xstrcpy(char *dst, char *src){ 2 if (!src) return; 3 if (!dst) return; 4 dst[0] = src[0]; 5 } 6 7 char global; 8 9 char *xmalloc() { 10 if (global) return &global; 11 return 0; 12 } 13 14 void npd_func_might(int flag, char *arg) { 15 char *p = &arg; 16 if (flag) p = xmalloc(); // xmalloc() may return NULL 17 if (arg) { p = arg; } // p may get a new value here 18 xstrcpy(p, "Hello"); // p will be dereferenced in xstrcpy() 19 } In the fixed code, *dst is checked for null at line 3 before the dereference. Related checkersExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |