CERT-EXP34-C_a
In this section:
Synopsis
Do not dereference null pointers.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
Dereferencing a null pointer is undefined behavior. On many platforms, dereferencing a null pointer results in abnormal program termination, but this is not required by the standard.
Coding standards
- CERT EXP34-C
Do not dereference null pointers
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
#include <string.h>
void * maybe_return_null(int num, void *p) {
if (num % 2) {
return NULL;
}
return p;
}
void example(void *usr_data, int length) {
int *ptr = malloc(sizeof(int));
ptr = maybe_return_null(length, ptr);
memcpy(ptr, usr_data, length);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <string.h>
void * maybe_return_null(int num, void *p) {
if (num % 2) {
return NULL;
}
return p;
}
void example(void *usr_data, int length) {
int *ptr = malloc(sizeof(int));
ptr = maybe_return_null(length, ptr);
if (ptr != NULL) {
memcpy(ptr, usr_data, length);
}
}