What happens if you dereference a null pointer?
Short answer
Dereferencing a null pointer is undefined behavior. In practice it often causes a segmentation fault/crash, but the standard doesn't guarantee that—optimizers may assume the pointer is non-null and behave unexpectedly.
Advertisement
AModel answer
Dereferencing a null pointer is undefined behavior. In practice it often causes a segmentation fault/crash, but the standard doesn't guarantee that—optimizers may assume the pointer is non-null and behave unexpectedly. Always check pointers (or use references/smart pointers/std::optional) before dereferencing when they might be null.
int* p = nullptr; int x = *p; // UB (often a crash)Real-world example
A missing null check on a lookup result crashes the app when the key is absent.
Likely follow-ups
- Is a crash guaranteed? | How do you avoid null dereference?
Related topics