Nearby lessons
89 of 124C - Pointer Initialization
Initialising a pointer means giving it a valid address before you use it. Learn the ways to do that — &variable, an array name, malloc, or NULL — and why an uninitialised pointer is one of C's most dangerous constructs.
Initialise from a Variable's Address
The most common form. Declare and point in a single statement:
The Uninitialised Pointer
int *p; creates a pointer holding whatever bytes were already on the stack. Dereferencing it writes to a random address — which may crash instantly, corrupt an unrelated variable, or appear to work until a customer runs it.NULL — Pointing Nowhere Deliberately
When you have no address yet, NULL says so explicitly. Unlike garbage, NULL can be tested:
NULL Is Not Zero-the-Value
NULL is a null pointer constant. Testing a pointer for truth tests whether it is non-null, which reads cleanly:
Initialise from an Array
An array name is already the address of its first element, so no & is needed:
Initialise from malloc — and Check It
malloc returns an address, or NULL if it fails. Checking is not optional:
Allocating an Array
Multiply by the count. calloc does the same and zero-fills the memory:
The Dangling Pointer
A pointer to memory that no longer exists. Freeing does not change the pointer — it only invalidates what it refers to:
Never Return a Local's Address
A local variable dies when its function returns, so its address is immediately worthless:
The Safe Pattern
Initialise to NULL, assign a real address, check before use, free, then NULL again:
Common Mistakes
| Mistake | Consequence |
|---|---|
int *p; *p = 5; | Writes to a random address |
int *p = 42; | 42 becomes the address, not the value |
Not checking malloc | Dereferences NULL on failure |
Using a pointer after free | Dangling pointer, undefined behaviour |
| Returning a local's address | Points at destroyed stack memory |
| Freeing twice | Heap corruption or a crash |
free(NULL) is explicitly safe and does nothing. That is why setting a pointer to NULL after freeing it also protects you against a double free — the second free becomes a harmless no-op.- Always initialise a pointer at declaration — to an address or to NULL.
- An uninitialised pointer holds garbage and crashes when dereferenced.
- NULL means "points to nothing" and is safe to test.
- Always check malloc's return value before using it.
- Set a pointer to NULL after freeing it.