Pointers and References
Values that hold the location of other values, and what goes wrong when that location is invalid.
What is it?
Every value in memory lives at an address, a number identifying where its bytes start. A pointer is a variable whose value is an address. Following that address to get the value stored there is called dereferencing.
Pointers let a function change its caller's data, let many parts of a program share one large object without copying it, and make linked structures like lists and trees possible.
In C and C++ pointers are explicit and raw: you can print them, do arithmetic on them, and point them anywhere, including at memory that no longer belongs to you. That power causes the most famous bugs in software: null pointer dereferences, dangling pointers to freed memory, and buffer overflows.
Managed languages (Java, Python, JavaScript, C#, Go to a degree) give you references instead: handles to objects that you can copy and compare but not do arithmetic on. The runtime guarantees a reference either points at a live object or is null/None, so dangling references are impossible, though null references are still very possible.
Explain like I'm 10
A pointer is a house address written on a piece of paper. Copying the paper doesn't copy the house. Going to the address is dereferencing. A null pointer is a blank piece of paper; a dangling pointer is the address of a house that's been demolished, where someone else may now be living.
Examples
Address, dereference, and changing a caller's variable (C)
#include <stdio.h>
void increment(int *counter) {
*counter = *counter + 1; /* change the value at the address */
}
int main(void) {
int count = 41;
int *pointer = &count; /* & takes the address of count */
printf("%p holds %d\n", (void *)pointer, *pointer);
increment(&count);
printf("count is now %d\n", count); /* 42 */
return 0;
}Pointer arithmetic and a dangling pointer (C)
int numbers[4] = {10, 20, 30, 40};
int *cursor = numbers; /* array decays to pointer to its first element */
cursor = cursor + 2; /* moves 2 * sizeof(int) bytes, not 2 bytes */
printf("%d\n", *cursor); /* 30 */
int *dangling(void) {
int local = 5;
return &local; /* BUG: local dies when the function returns */
}Adding n to a pointer advances it by n elements of its type. Returning the address of a local variable gives the caller a dangling pointer to a stack slot that will be reused by the next call.
References in a managed language (Java)
List<String> first = new ArrayList<>();
List<String> second = first; // copies the reference, not the list
second.add("shared");
System.out.println(first); // [shared]: both names refer to one object
second = new ArrayList<>(); // rebinds second only
System.out.println(first); // still [shared]Java passes and assigns references by value. You can mutate the shared object through either reference, but reassigning one variable never affects the other.
How it works
Memory is a large array of bytes, and an address is an index into it (a virtual address that the CPU's memory management unit translates to physical memory). A pointer is typically 8 bytes on a 64-bit machine.
The pointer's type tells the compiler two things: how many bytes to read when you dereference it, and how far p + 1 moves (sizeof(*p) bytes). array[i] in C is literally defined as *(array + i).
Null is a reserved address (0 in practice) that means "points nowhere". The OS leaves the lowest page of the address space unmapped, so dereferencing null usually crashes immediately with a segmentation fault. In C and C++ it is still undefined behavior, so the compiler may assume it never happens and optimize accordingly.
A dangling pointer still holds an address, but the memory there has been freed or has gone out of scope. Reading it might return stale data, garbage, or someone else's data; writing through it corrupts whatever lives there now.
Managed references are pointers the runtime controls. You can't do arithmetic or cast integers to them, and the garbage collector only frees an object when no reference to it remains, so references can't dangle. A moving collector may even relocate objects and update every reference behind your back. C++ references (int&) are different again: an alias that must be bound once and can't be null or reseated.
Variable Address Value
-------- ------- -----
count 0x1000 41
pointer 0x1008 0x1000 ---+
| *pointer follows the arrow
v
0x1000: 41
int numbers[4] at 0x2000 (4-byte ints):
0x2000 0x2004 0x2008 0x200C
[ 10 ] [ 20 ] [ 30 ] [ 40 ]
^ ^
numbers numbers + 2Why does it exist?
Programs need to share data without copying it, let functions modify data they were given, and build structures whose pieces are linked rather than laid out contiguously. Hardware works in addresses, so low-level languages expose them directly. Managed languages keep the useful part (sharing and indirection) and remove the dangerous part (arithmetic and manual lifetimes).
When to use it
- Raw pointers in C/C++ for systems work: OS kernels, drivers, memory-mapped I/O, custom allocators, and performance-critical data structures. - Passing a pointer or reference to avoid copying large structs, or to let a function fill in an output. - Building linked lists, trees and graphs where nodes refer to each other. - In C++, prefer references and smart pointers (unique_ptr, shared_ptr) and reach for raw pointers only for non-owning observation.
When not to use it
- Don't use raw owning pointers in modern C++ or unsafe Rust when an ownership type would do; they're where leaks and dangling pointers come from. - Don't use pointer arithmetic to walk data when indexing or iterators express the same thing; they're bounds-checkable and easier to read. - Don't pass a pointer just to "make it faster" for small values like ints; copying 4 or 8 bytes is as cheap as copying an address.
Common mistakes
Returning a pointer or reference to a local variable. The stack frame is gone once the function returns, so the pointer dangles.
Dereferencing a pointer without checking for null, especially return values from
malloc, lookups, or optional fields.Thinking
p + 1moves one byte. It moves one element, soint *padvances bysizeof(int).Using a pointer into a growable container (a C++
vectorelement, a Go slice) after the container reallocates; the old storage is freed and the pointer dangles.In managed languages, assuming
b = acopies an object. It copies the reference, so mutations throughbshow up througha.
Practice exercises
- Easy:
Write a C function
void swap(int *a, int *b)that swaps two integers in the caller, and explain whyvoid swap(int a, int b)can't work. - Medium:
Implement a singly linked list in C with
push_front,find, andfree_all. Use AddressSanitizer to prove there are no leaks or use-after-free bugs, then deliberately add one and read the report. - Hard:
Write
my_strlenandmy_memcpyin C using only pointer arithmetic (no indexing). Then explain what happens if the source and destination regions overlap, and writemy_memmovethat handles it.
Interview questions
What is the difference between a pointer and a reference?
A pointer is a variable holding an address: it can be null, reassigned, and (in C/C++) used in arithmetic. A C++ reference is an alias that must be initialized, can't be null in valid code, and can't be reseated. A managed-language reference is a GC-controlled handle: nullable and reassignable, but with no arithmetic and no dangling.
What is a dangling pointer, and how do you get one?
A pointer to memory that is no longer valid: freed heap memory, a local variable whose function has returned, or a container element after the container reallocated. Using it is undefined behavior and may read stale data or corrupt live data.
What happens when you dereference a null pointer?
In C and C++ it's undefined behavior. In practice it usually causes a segmentation fault because the OS leaves address 0 unmapped, but the compiler may also optimize code assuming it can't happen. In Java or C# it throws NullPointerException / NullReferenceException.
How does pointer arithmetic work in C?
Adding n to a T * advances the address by n * sizeof(T). Subtracting two pointers into the same array gives the element distance. a[i] is defined as *(a + i). Arithmetic is only defined within one array object (plus one past its end).
Why can't Java have dangling references?
Java gives no way to free an object explicitly or to compute an address. The GC reclaims an object only when nothing references it, so any reference you hold always points to a live object or is null.
Is Java pass-by-reference?
No. Java is always pass-by-value; for objects the value passed is a reference. The method can mutate the shared object, but reassigning the parameter has no effect on the caller's variable.
What is a double free, and why is it dangerous?
Calling free twice on the same pointer. Allocators keep metadata in and around freed blocks, so a second free can corrupt free lists. Attackers can exploit this to make later allocations overlap and overwrite chosen memory.
How do smart pointers reduce pointer bugs in C++?
They encode ownership in the type. unique_ptr has one owner and frees on scope exit; shared_ptr reference-counts shared ownership; weak_ptr observes without owning and breaks cycles. Frees become automatic and ownership transfers become explicit with std::move.
Why does Rust have both references and raw pointers?
Safe references (&T, &mut T) are checked by the borrow checker: always valid and either shared-read or exclusive-write, never both. Raw pointers (*const T, *mut T) skip those checks for FFI and low-level code and can only be dereferenced in an unsafe block, which marks where a human must uphold the invariants.