NPD.GEN.MUSTAssigned null-pointer constant value 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.GEN.MUST checker flags situations in which a pointer that's been assigned a null constant value 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 void xstrcpy(char *dst, char *src) { 2 if (!src) return; 3 dst[0] = src[0]; 4 } 5 6 char global_buf[256]; 7 8 void npd_gen_must(int flag) { 9 char *p = global_buf; 10 if (flag) p = 0; // NULL is assigned to p 11 xstrcpy(p, "Hello"); 12 } Klocwork flags a defect in this example, because constant NULL is assigned to 'p' if condition 'flag' is true and then dereferenced through a call to function xstrcpy. This 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_buf[256]; 8 9 void npd_gen_must(int flag) { 10 char *p = global_buf; 11 if (flag) p = 0; 12 xstrcpy(p, "Hello"); 13 } In the fixed code, *dst is checked for null at line 3. Related checkersExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |