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.