Null reference creation and null pointer dereference
Detects the creation of null references and null pointer dereferences.
Overview
In Xcode 9 and later, you can use this check to detect the creation of null references and null pointer dereferences. Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.
Creating a null reference in C++
The following example demonstrates how to create a null reference. References in C++ must be nonnull:
int &x = *(int *)nullptr; // Error: null referenceSolution
Use a pointer instead.
int *x = nullptr; // CorrectMember access through a null pointer in C++
The following code makes a member call on an object with a null address. The compiler may remove the null check on the this pointer because it requires the pointer to be nonnull.
struct A {
int x;
int getX() {
if (!this) { // Warning: redundant null check may be removed
return 0;
}
return x; // Warning: 'this' pointer is null, but is dereferenced here
}
};
A *a = nullptr;
int x = a->getX(); // Error: member access through null pointerSolution
Avoid calling methods on null objects.
See Also
Undefined Behavior Sanitizer
Misaligned pointerInvalid Boolean valueOut-of-bounds array accessInvalid enumeration valueReaching of unreachable pointDynamic type violationInvalid float castDivision by zeroNonnull argument violationNonnull return value violationNonnull variable assignment violationInvalid object sizeInvalid shiftInteger overflowInvalid variable-length array