LIB-return-null
Synopsis
A pointer is assigned using a library function that can return NULL as an error value. This pointer is subsequently dereferenced without checking its value.
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
A pointer is assigned using a library function that can return NULL as an error value. This pointer is subsequently dereferenced without checking its value, which might lead to a NULL dereference. Not inspecting the return value of any function returning a pointer before dereferencing it, might cause a crash. These functions are inspected: malloc(), calloc(), realloc(), memchr(), strchr(), strpbrk(), strrchr(), strstr(), strtok(), gmtime(), getenv(), and bsearch().
Coding standards
- CERT FIO04-C
Detect and handle input and output errors
- CWE 252
Unchecked Return Value
- CWE 394
Unexpected Status Code or Return Value
- CWE 690
Unchecked Return Value to NULL Pointer Dereference
Code examples
The following code example fails the check and will give a warning:
#include <string.h>
void example(char c) {
char* cp = strchr("Hello", c);
printf("%c\n", *cp); // cp is dereferenced uncon-
// ditionally, but may be NULL
}
The following code example passes the check and will not give a warning about this issue:
#include <string.h>
void example(char c) {
char* cp = strchr("Hello", c);
if (cp){
printf("%c\n", *cp); // OK - cp checked against
// NULL
}
}