Wild Pointer
A wild pointer is a pointer that has never been given a valid value. Its bits are leftover stack or heap garbage. Even reading the pointer, let alone dereferencing it, is undefined behavior.
Detailed Explanation
int *p; at block scope does not put NULL in p. It puts whatever was in that stack slot. if (p != NULL) is already undefined: you read an indeterminate value. The branch you see today is not a promise.
This is different from a dangling pointer, which once pointed at a real object, and from NULL, which is a defined "nowhere." A wild pointer never pointed at anything you know about. It might accidentally equal a real address, which is worse: the dereference appears to work and corrupts unrelated data.
Initialization is the whole fix. int *p = NULL; if you have no object yet. int *p = &x; or int *p = malloc(...) if you do. Static and file-scope pointers are zeroed and so start as null, which is defined. Automatic pointers are the hazard.
Structs have the same rule. struct Node n; has a wild n.next. calloc or {0} makes it NULL. A malloc of the struct without writing next leaves next wild; the next walk is a lottery.
Compilers can warn (-Wuninitialized, -Wmaybe-uninitialized). They miss cases that pass through another function. Tools that poison uninitialized memory (ASan + MemorySanitizer, Valgrind) catch reads. Turn them on. Do not "initialize" a pointer by assigning p = p or by casting garbage to a pointer type.
Code Examples
#include <stdio.h>
int main(void)
{
int *p = NULL; /* defined empty, not wild */
int x = 5;
p = &x;
printf("%d\n", *p); /* prints: 5 */
return 0;
}#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main(void)
{
struct Node *n = calloc(1, sizeof *n);
if (n == NULL) {
return 1;
}
n->value = 1;
printf("%d\n", n->next == NULL); /* prints: 1 */
free(n);
return 0;
}Common Gotchas
Comparing an uninitialized pointer to `NULL` is undefined behavior
initialize it first.
`malloc` of a struct does not give you `NULL` members
they are wild until you write them.
File-scope pointers start as `NULL`
block-scope pointers do not.
A wild pointer that happens to match a real object will corrupt that object when
A wild pointer that happens to match a real object will corrupt that object when written