Weaknesscore
NULL pointer dereference
Also called null dereference, NPD, null deref, NullPointerException, NPE, nil pointer dereference, cwe-476.
A NULL pointer dereference happens when a program uses a pointer or a reference that is NULL as if it were valid, so the program crashes or, in rare cases, uses memory at address zero.
- CWE
- CWE-476
- Abstraction
- base
- OWASP Top 10 (2025)
- A10
- CWE Top 25 (2025)
- rank 13
- Languages affected
- c, cpp, java, csharp, go, python, javascript
Description
A pointer is an address. A program uses the special value NULL to say that a pointer points to nothing: a lookup found no record, an allocation failed, or a field is not set yet. NULL is not an object. A NULL pointer dereference happens when the program reads or writes through the pointer as if it pointed to a valid object.1 Languages with references have the same weakness under other names. Java calls it a NullPointerException, C# a NullReferenceException, and Go a nil pointer dereference.1
The root cause is that one type carries two meanings. In C, the type struct user * means "a user" and also "maybe a user". The compiler accepts u->quota for both meanings, so it cannot tell the developer that a check is missing. The Rust book says that this property is pervasive, so the use of a null value as a value that is not null is an extremely common error.7 The design history of the null reference is on the page Null reference.
The missing check is usually on a rare path. CWE-476 says that the weakness is frequently resultant from rarely encountered error conditions and race conditions.1 A test calls the lookup with a name that exists, and the error path never runs. Its Example 1 calls gethostbyaddr for an address that has no host name, so the call returns NULL, and the code copies hp->h_name without a check. CWE files the missing check as CWE-252, an unchecked return value.1 Other causes are a variable that is not initialized, a structure that is used before it is set up, and a pointer that is cleared after a free. The page Use after free shows that clearing a pointer turns a later use into a NULL dereference, which is a smaller risk.
The usual result is a crash, so the main impact is on availability. A crash of a server is a denial of service. CWE-476 says that even with exception handling, it can be hard to return the program to a safe state. In rare cases, when NULL is the address 0x0 and privileged code can access that address, a dereference can read or write memory and can lead to code execution.1
CWE-476 is a base weakness. It is rank 13 in the 2025 CWE Top 25, with no CVEs in the CISA catalogue of known exploited vulnerabilities, up from rank 21 the year before.2 The OWASP Top 10:2025 lists it as a notable weakness of A10:2025 Mishandling of Exceptional Conditions, a category that the 2025 edition added.3
History
In August 2009, Tavis Ormandy and Julien Tinnes published CVE-2009-2692.4 Tinnes wrote that it affected all 2.4 and 2.6 Linux kernels since 2001 on all architectures. Functions such as sock_sendpage did not check for NULL pointers before they called operations in the proto_ops structure. The kernel relied on correct initialization of those structures with stubs, and some structures were not initialized.4 The CVE record says that a local user could gain privileges, because a process could map page zero, and the kernel then ran code from that page.5 The case showed that a NULL dereference in privileged code is not only a crash.
Vulnerable code
find_user returns NULL when no user has the name. The caller does not check, and it reads u->quota. The second name is the classic demonstration input, a name that does not exist. The block builds with UndefinedBehaviorSanitizer, which has a check for the use of a null pointer.6
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <string.h>
struct user {
const char *name;
int quota;
};
static struct user users[] = {{"alice", 10}, {"bob", 20}};
// Returns the user with this name, or NULL if there is none.
struct user *find_user(const char *name) {
for (size_t i = 0; i < sizeof users / sizeof users[0]; i++) {
if (strcmp(users[i].name, name) == 0) {
return &users[i];
}
}
return NULL;
}
int main(void) {
const char *names[] = {"alice", "nobody"};
for (int i = 0; i < 2; i++) {
struct user *u = find_user(names[i]);
printf("%s: quota %d\n", names[i], u->quota); // u can be NULL
}
}
UndefinedBehaviorSanitizer reports a member access within null pointer of type 'struct user'. Without the sanitizer, the process usually stops with a segmentation fault. The function and the call look correct. Only the comment on find_user says that NULL is a possible result.
Fixed code
The fix checks the result before each use, and it handles the missing user as a normal case. The block builds with AddressSanitizer and UndefinedBehaviorSanitizer, and both stay silent.
#include <stdio.h>
#include <string.h>
struct user {
const char *name;
int quota;
};
static struct user users[] = {{"alice", 10}, {"bob", 20}};
// Returns the user with this name, or NULL if there is none.
struct user *find_user(const char *name) {
for (size_t i = 0; i < sizeof users / sizeof users[0]; i++) {
if (strcmp(users[i].name, name) == 0) {
return &users[i];
}
}
return NULL;
}
int main(void) {
const char *names[] = {"alice", "nobody"};
for (int i = 0; i < 2; i++) {
struct user *u = find_user(names[i]);
if (u == NULL) {
printf("%s: no such user\n", names[i]);
continue;
}
printf("%s: quota %d\n", names[i], u->quota);
}
}
alice: quota 10
nobody: no such user
CWE-476 rates a check of every return value as moderately effective. A check is not enough when another thread can change the pointer between the check and the use, so the check and the use must be under the same lock.1
Types that say "maybe"
A check that the developer must remember is the weakest fix. A stronger fix puts "maybe absent" in the type, so the compiler refuses the use without a check. Rust has no null. Its Option<T> has the variants Some(T) and None, and an Option<T> is not a T.7 The program below does not compile, because it uses the result of a lookup as the value itself.
This code does not compile, on purpose.
fn find_quota(name: &str) -> Option<i32> {
match name {
"alice" => Some(10),
"bob" => Some(20),
_ => None,
}
}
fn main() {
for name in ["alice", "nobody"] {
let quota: i32 = find_quota(name);
println!("{name}: quota {quota}");
}
}
The compiler reports mismatched types: it expected i32 and found Option<i32>. The fix is a match or an if let that handles None, and the Rust example file shows it.
Kotlin types do not include null unless the type has a ?. The Kotlin documentation says that the only possible causes of a NullPointerException are an explicit throw, the !! operator, problems during initialization and Java interoperation.13 TypeScript with strictNullChecks gives null and undefined their own types and reports a type error where a value is expected.14 C# nullable reference types are a compile-time feature. The compiler warns when the code can dereference a variable that may be null, and the runtime behavior does not change.12 Java, Python and JavaScript find the error only at run time. Java has Optional for a method that can return "no result".10
How to detect it
- Sanitizers. Build the tests with
-fsanitize=null, which is part of-fsanitize=undefined. It reports the use of a null pointer at the line of the use.6 - Fuzzing and error injection. CWE-476 rates automated dynamic analysis such as fuzzing as moderately effective. It also suggests manual tests that force rare error conditions, such as low memory.1 Make the lookup fail, the allocation fail and the file open fail, and see what the caller does.
- Static analysis. CodeQL query
cpp/inconsistent-null-checkfinds a call whose result is not checked for NULL when most other calls to the same function check it.17 Queriesjava/dereferenced-value-may-be-nullandcs/dereferenced-value-may-be-nullfind a variable that may be null on some path to a dereference.1819 In C#, the nullable warnings of the compiler do the same work.12 - Code review. For each function that can return NULL, find every caller and check that it handles NULL. Look for an error path that sets a pointer to NULL and then falls through, for structures with function pointers that are not all set, and for a check that comes after the dereference.
How to prevent it
- Use types that cannot be null. CWE-476 lists language selection first.1 Use
Optionin Rust, types without?in Kotlin,strictNullChecksin TypeScript and nullable reference types with warnings as errors in C#.7131412 - Return an explicit absence. In Java, return
Optionalfrom a lookup instead of null.10 In Go and C, return a second value or an error code with the pointer, and check it. - Check every result that can be NULL. Check the pointer before the use, and use a lock in concurrent code so that the pointer does not change between the check and the use.1
- Initialize everything. CWE-476 asks to initialize all variables explicitly, at the declaration or immediately before the first use. Fill every function pointer in a table with a valid stub.14
- Fail closed. When a value is absent, refuse the operation with a clear error. OWASP asks to handle each exceptional condition where it occurs, and to roll back every part of a transaction that fails part way.3
Real cases
| Case | Date | What happened |
|---|---|---|
| CVE-2004-0079 | published 2004-03-18 | A crafted SSL/TLS handshake triggered a null dereference in do_change_cipher_spec in OpenSSL 0.9.6c to 0.9.6k and 0.9.7a to 0.9.7c, and crashed the server.201 |
| CVE-2009-2692 | published 2009-08-14 | The Linux kernel did not initialize all function pointers in proto_ops structures. A local user could trigger a NULL pointer dereference and gain privileges.54 |
| CVE-2020-29652 | published 2020-12-17 | A nil pointer dereference in golang.org/x/crypto/ssh let remote attackers cause a denial of service against SSH servers.211 |
This code raises AttributeError, on purpose.
from dataclasses import dataclass
@dataclass
class User:
quota: int
users = {"alice": User(10), "bob": User(20)}
for name in ["alice", "nobody"]:
user = users.get(name) # None when the key is missing
print(f"{name}: quota {user.quota}")
dict.get returns None for a missing key. None has no attribute quota, so the attribute reference raises AttributeError: 'NoneType' object has no attribute 'quota'.
from dataclasses import dataclass
@dataclass
class User:
quota: int
users = {"alice": User(10), "bob": User(20)}
def find_user(name: str) -> User | None:
return users.get(name)
for name in ["alice", "nobody"]:
user = find_user(name)
if user is None:
print(f"{name}: no such user")
continue
print(f"{name}: quota {user.quota}")
alice: quota 10
nobody: no such user
- Verdict: absent. Any name can hold
None, and the interpreter finds the error only when the line runs. The error is an exception, not a memory access. - Write
User | Nonein the type hints of functions that can returnNone. A type checker then reports a use without a check. The interpreter does not check hints. - Test with
is None, not with a truth test, because an empty value is also false.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <iostream>
#include <map>
#include <string>
struct User {
int quota;
};
const std::map<std::string, User> users = {{"alice", {10}}, {"bob", {20}}};
// Returns the user, or nullptr if there is none.
const User* find_user(const std::string& name) {
auto it = users.find(name);
return it == users.end() ? nullptr : &it->second;
}
int main() {
for (std::string name : {"alice", "nobody"}) {
const User* u = find_user(name);
std::cout << name << ": quota " << u->quota << "\n"; // u can be nullptr
}
}
UndefinedBehaviorSanitizer reports a member access within null pointer of type 'const User'. The raw pointer has the same two meanings as in C.
#include <iostream>
#include <map>
#include <optional>
#include <string>
struct User {
int quota;
};
const std::map<std::string, User> users = {{"alice", {10}}, {"bob", {20}}};
// The return type says that the user can be absent.
std::optional<User> find_user(const std::string& name) {
auto it = users.find(name);
if (it == users.end()) {
return std::nullopt;
}
return it->second;
}
int main() {
for (std::string name : {"alice", "nobody"}) {
if (auto u = find_user(name)) {
std::cout << name << ": quota " << u->quota << "\n";
} else {
std::cout << name << ": no such user\n";
}
}
}
alice: quota 10
nobody: no such user
- Verdict: stdlib.
std::optionalputs absence in the type, and a reference cannot be null. Raw pointers and smart pointers can still be null. *optandopt->on an emptystd::optionalare undefined behavior. Test the optional first, or callvalue(), which throwsstd::bad_optional_access.- Return a reference when a value is always present, and an optional when it can be absent.
This code raises NullPointerException, on purpose.
import java.util.Map;
public class Main {
record User(int quota) {}
static final Map<String, User> USERS = Map.of("alice", new User(10), "bob", new User(20));
public static void main(String[] args) {
for (String name : new String[] {"alice", "nobody"}) {
User u = USERS.get(name); // null when the key is missing
System.out.println(name + ": quota " + u.quota());
}
}
}
Map.get returns null for a missing key. The call u.quota() on null throws NullPointerException.
import java.util.Map;
import java.util.Optional;
public class Main {
record User(int quota) {}
static final Map<String, User> USERS = Map.of("alice", new User(10), "bob", new User(20));
// The return type says that the user can be absent.
static Optional<User> findUser(String name) {
return Optional.ofNullable(USERS.get(name));
}
public static void main(String[] args) {
for (String name : new String[] {"alice", "nobody"}) {
String line = findUser(name)
.map(u -> "quota " + u.quota())
.orElse("no such user");
System.out.println(name + ": " + line);
}
}
}
alice: quota 10
nobody: no such user
- Verdict: stdlib. Every reference type includes
null, and the compiler does not check that the code tests it.java.util.Optionalmarks a result that can be absent. - Return
Optionalfrom a lookup, and do not returnnullfrom a method whose type isOptional. - Use
Objects.requireNonNullat the start of a method to fail at the boundary, not deep in the code. - Unboxing a
nullIntegertointalso throwsNullPointerException.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
struct socket_ops {
int (*open)(void);
int (*send)(const char *data);
};
static int plain_open(void) {
return 0;
}
// This family does not set send, so send is NULL.
static const struct socket_ops packet_ops = {.open = plain_open};
int main(void) {
const struct socket_ops *ops = &packet_ops;
printf("open: %d\n", ops->open());
printf("send: %d\n", ops->send("hello")); // calls through NULL
}
A table of operations leaves one function pointer out, so the pointer is NULL. The call through it jumps to address zero. AddressSanitizer reports a SEGV on unknown address. This is the shape of CVE-2009-2692, where the kernel relied on every proto_ops structure being filled.
#include <stdio.h>
struct socket_ops {
int (*open)(void);
int (*send)(const char *data);
};
static int plain_open(void) {
return 0;
}
// The stub refuses the operation with an error code.
static int no_send(const char *data) {
(void)data;
return -1;
}
// Every member has a value, so no call goes through NULL.
static const struct socket_ops packet_ops = {.open = plain_open, .send = no_send};
int main(void) {
const struct socket_ops *ops = &packet_ops;
printf("open: %d\n", ops->open());
printf("send: %d\n", ops->send("hello"));
}
open: 0
send: -1
- Verdict: absent. C has no type for "maybe a pointer". Every pointer can be NULL, and the compiler does not check that the code tests it.
- Check the result of every function that can return NULL, such as
malloc,fopen,getenvand lookups. - Fill every member of a table of function pointers with a function or a stub that returns an error.
- Build the tests with
-fsanitize=undefined, which includes the check-fsanitize=null.
This code raises NullReferenceException, on purpose.
var users = new Dictionary<string, User> { ["alice"] = new User(10), ["bob"] = new User(20) };
foreach (var name in new[] { "alice", "nobody" })
{
User u = users.GetValueOrDefault(name)!; // null when the key is missing
Console.WriteLine($"{name}: quota {u.Quota}");
}
record User(int Quota);
GetValueOrDefault returns null for a missing key. The ! operator tells the compiler that the value is not null, so the nullable warning goes away, but the value is still null. The access to u.Quota throws NullReferenceException.
var users = new Dictionary<string, User> { ["alice"] = new User(10), ["bob"] = new User(20) };
foreach (var name in new[] { "alice", "nobody" })
{
if (users.TryGetValue(name, out User? u))
{
Console.WriteLine($"{name}: quota {u.Quota}");
}
else
{
Console.WriteLine($"{name}: no such user");
}
}
record User(int Quota);
alice: quota 10
nobody: no such user
- Verdict: native. With nullable reference types,
UserandUser?are different to the compiler, and it warns when the code can dereference a value that may be null. The runtime does not change, so a warning that is ignored is still a crash. - Treat the nullable warnings as errors in the project file.
- Each
!operator is a place to review. It hides the warning and does not check anything. - Use
TryGetValue,?.and??on values that can be absent.
This code raises TypeError, on purpose.
const users = new Map([
["alice", { quota: 10 }],
["bob", { quota: 20 }],
]);
for (const name of ["alice", "nobody"]) {
const user = users.get(name); // undefined when the key is missing
console.log(`${name}: quota ${user.quota}`);
}
Map.prototype.get returns undefined for a missing key. Reading a property of undefined throws TypeError: Cannot read properties of undefined.
const users = new Map([
["alice", { quota: 10 }],
["bob", { quota: 20 }],
]);
for (const name of ["alice", "nobody"]) {
const quota = users.get(name)?.quota;
if (quota === undefined) {
console.log(`${name}: no such user`);
continue;
}
console.log(`${name}: quota ${quota}`);
}
alice: quota 10
nobody: no such user
- Verdict: native.
nullandundefinedexist in the language, and the error is found only at run time. The operator?.stops and givesundefinedwhen the value on its left isnullorundefined. ?.hides the absence. Handle theundefinedresult, as the fixed block does, so that the absence does not move to a later line.- Use TypeScript with
strictNullChecksto find a missing check before the code runs.
This code panics, on purpose.
package main
import "fmt"
type User struct {
Quota int
}
var users = map[string]*User{"alice": {Quota: 10}, "bob": {Quota: 20}}
func main() {
for _, name := range []string{"alice", "nobody"} {
u := users[name] // nil when the key is missing
fmt.Printf("%s: quota %d\n", name, u.Quota)
}
}
A map returns the zero value of its element type for a missing key, and the zero value of a pointer is nil. The selector u.Quota on a nil pointer causes a run-time panic: invalid memory address or nil pointer dereference.
package main
import "fmt"
type User struct {
Quota int
}
var users = map[string]*User{"alice": {Quota: 10}, "bob": {Quota: 20}}
func main() {
for _, name := range []string{"alice", "nobody"} {
u, ok := users[name]
if !ok || u == nil {
fmt.Printf("%s: no such user\n", name)
continue
}
fmt.Printf("%s: quota %d\n", name, u.Quota)
}
}
alice: quota 10
nobody: no such user
- Verdict: absent. Pointers, maps, slices, channels, functions and interfaces can be
nil, and the compiler does not check that the code tests them. - Use the two-value form
v, ok := m[key], and checkerrbefore the other results of a function. - Store values instead of pointers when the zero value is a valid value.
- A nil dereference panics and does not read memory. A server that does not recover the panic stops, so the impact is a denial of service, as in CVE-2020-29652.
This code panics, on purpose.
fn find_quota(name: &str) -> Option<i32> {
match name {
"alice" => Some(10),
"bob" => Some(20),
_ => None,
}
}
fn main() {
for name in ["alice", "nobody"] {
let quota = find_quota(name).unwrap();
println!("{name}: quota {quota}");
}
}
unwrap on None panics, and the message says that Option::unwrap() was called on a None value. The panic is defined behavior and stops the thread, but it is still a crash. Each unwrap and expect is a place to review.
fn find_quota(name: &str) -> Option<i32> {
match name {
"alice" => Some(10),
"bob" => Some(20),
_ => None,
}
}
fn main() {
for name in ["alice", "nobody"] {
match find_quota(name) {
Some(quota) => println!("{name}: quota {quota}"),
None => println!("{name}: no such user"),
}
}
}
alice: quota 10
nobody: no such user
- Verdict: native. Safe Rust has no null references.
Option<T>is a different type fromT, so the compiler refuses a use of the value until the code handlesNone. unwrapandexpectturn aNoneinto a panic. Usematch,if let,?orunwrap_oron values that come from input.- Raw pointers in
unsafecode can be null. Useptr::NonNullor check withis_nullbefore a dereference.
References
- CWE-476: NULL Pointer Dereference, Description; Alternate Terms; Common Consequences; Potential Mitigations; Weakness Ordinalities; Detection Methods; Demonstrative Examples, Example 1; Observed Examples
- 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 13, CVEs in KEV, Rank Last Year
- OWASP Top 10:2025, A10:2025 Mishandling of Exceptional Conditions, Background; List of Mapped CWEs
- Julien Tinnes, Linux NULL pointer dereference due to incorrect proto_ops initializations (CVE-2009-2692), August 13, 2009, the opening paragraphs
- CVE-2009-2692, Linux kernel, the description and the publication date
- Clang documentation, UndefinedBehaviorSanitizer, Available checks, -fsanitize=null
- The Rust Programming Language, Defining an Enum, The Option Enum and Its Advantages Over Null Values
- The Go Programming Language Specification, Address operators
- Java SE 25 API, java.lang.NullPointerException, the class description
- Java SE 25 API, java.util.Optional, the class description, API Note
- .NET API reference, NullReferenceException, the class description; Remarks
- C# fundamentals, Nullable reference types, the opening section
- Kotlin documentation, Null safety, the opening section, the only possible causes of an NPE
- TypeScript TSConfig reference, strictNullChecks, the option description
- The Python Standard Library, Built-in Exceptions, AttributeError
- MDN Web Docs, Optional chaining (?.), Description
- CodeQL query help, Inconsistent null check (cpp/inconsistent-null-check), the query description; Recommendation
- CodeQL query help, Dereferenced variable may be null (java/dereferenced-value-may-be-null), the query description; Recommendation
- CodeQL query help, Dereferenced variable may be null (cs/dereferenced-value-may-be-null), the query description; Recommendation
- CVE-2004-0079, OpenSSL, the description and the publication date
- CVE-2020-29652, golang.org/x/crypto/ssh, the description and the publication date
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 59SZGS Edit this page History Report an error Markdown