<!--
{
  "documentType" : "article",
  "framework" : "Xcode",
  "identifier" : "/documentation/Xcode/null-reference-creation-and-null-pointer-dereference",
  "metadataVersion" : "0.1.0",
  "role" : "article",
  "title" : "Null reference creation and null pointer dereference"
}
-->

# 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:

```occ
int &x = *(int *)nullptr; // Error: null reference
```

#### Solution

Use a pointer instead.

```occ
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`.

```occ
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
```

> Important: Always avoid null checks on the `this` pointer.

#### Solution

Avoid calling methods on null objects.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)