Contents

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 reference

Solution

Use a pointer instead.

int *x = nullptr; // Correct

Member 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 pointer

Solution

Avoid calling methods on null objects.

See Also

Undefined Behavior Sanitizer