Attempting to dereference Dereferencing a null pointer results in undefined behavior.
...
This noncompliant code example is derived from a real-world example taken from a vulnerable version of the libpng
library as deployed on a popular ARM-based cell phone [Jack 2007]. The libpng
library allows applications to read, create, and manipulate PNG (Portable Network Graphics) raster image files. The libpng
library implements its own wrapper to malloc()
that returns a null pointer on error or on being passed a 0-byte-length argument.
This code also violates void MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <png.h> /* From libpng */ void func(png_structp png_ptr, int length) { png_charp chunkdata; chunkdata = (png_charp)png_malloc(png_ptr, length + 1); /* ... */ } |
...
In this noncompliant code example, input_str
is copied into dynamically allocated memory referenced by str
. If malloc()
fails, it returns a null pointer that is assigned to str
. When str
is dereferenced in memcpy()
, the program exhibits undefined behavior. Additionally, if input_str
is a null pointer, the call to strlen()
dereferences a null pointer, resulting in undefined behavior. This code also violates void MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <string.h> #include <stdlib.h> void f(const char *input_str) { size_t size = strlen(input_str) + 1; char *c_str = (char *)malloc(size); memcpy(c_str, input_str, size); /* ... */ free(c_str); c_str = NULL; /* ... */ } |
...
This noncompliant code example can be found in is from a version of drivers/net/tun.c
and affects Linux kernel 2.6.30 [Goodin 2009]:
...
CERT C Secure Coding Standard | void MEM32-C. Detect and handle memory allocation errors |
CERT C++ Secure Coding Standard | EXP34-CPP. Ensure a null pointer is not dereferenced |
CERT Oracle Secure Coding Standard for Java | EXP01-J. Never dereference null pointers |
ISO/IEC TR 24772:2013 | Pointer Casting and Pointer Type Changes [HFC] Null Pointer Dereference [XYH] |
ISO/IEC TS 17961 | Dereferencing an out-of-domain pointer [nullref] |
MITRE CWE | CWE-476, NULL Pointer dereference |
...
[Goodin 2009] | |
[Jack 2007] | |
[Liu 2009] | |
[van Sprundel 2006] | |
[Viega 2005] | Section 5.2.18, "Null-Pointer Dereference" |
...
...