The standard C library includes a variety of functions for string and general memory manipulations. Many of these functions require valid
parameters and when given values outside a function’s domain, the behavior is undefined. Functions like strlen, memset,
memcpy, qsort, fread, etc., for instance, require non-NULL parameters, and passing a
NULL value introduces undefined behavior. In that case, the application may crash or, even worse, silently lose data or produce incorrect
results.
Consider the following code. If the pointer-typed variable buf is NULL due to a failed memory allocation, for instance,
the call to memset() will cause undefined behavior.
#include <string.h>
void process_buffer(char *buf, size_t size) {
// Call to `memset()` may lead to undefined behavior, if `buf` is NULL.
memset(buf, 0, size);
}
Similarly, if for some reason a NULL pointer slips through and reaches the string manipulation code shown in the following, the
application’s behavior is undefined.
#include <string.h>
int compare_strings(const char *str_a, const char *str_b) {
// Both functions `strlen()` and `strncmp()` may not receive a `NULL` pointer.
size_t len_a = strlen(str_a);
size_t len_b = strlen(str_b);
size_t min = (len_a <= len_b) ? len_a : len_b;
return strncmp(str_a, str_b, min);
}
Hence, users have to ensure that the C standard library functions' preconditions are met and valid parameters are passed.
The C library functions that are considered by this rule and that require non-NULL pointer parameters are listed in this rule’s
Resources section.
What is the potential impact?
If an argument to one of the C library functions mentioned by this rule is a NULL pointer, the behavior of the application is
undefined.
When a program comprises undefined behavior, the compiler no longer needs to adhere to the language standard, and the program has no meaning
assigned to it.
Due to the resulting NULL pointer dereferences in the C library functions, the application might just crash, but in the worst case,
the application may appear to execute correctly, while losing data or producing incorrect results.
Besides affecting the application’s availability, NULL pointer dereferences may lead to code execution, in rare circumstances. If
NULL is equivalent to the 0x0 memory address that can be accessed by privileged code, writing and reading memory is
possible, which compromises the integrity and confidentiality of the application.