Pointers and Memory in C
Addresses, pointer types, dynamic allocation and the rules that keep memory access defined. Pointers, pointer arithmetic, function pointers and dynamic allocation have their own pages earlier in this subject.
This is an overview — pick a sub-topic below.
Sub-topics (13)
Pointer to Pointer
A pointer holding the address of another pointer (`int **pp`).
Void Pointers
`void *` is a generic pointer to any object type.
Array Pointers
A pointer to a whole array, e.g. `int (*p)[4]` — different from an array of pointers `int *p[4]`.
Pointers and Strings
Walk strings with `char *` until the `'\0'`.
const Pointers
Where `const` sits decides what is read-only.
malloc
Allocates uninitialised memory on the heap.
calloc
Allocates zero-initialised memory for `n` elements and checks the multiplication for overflow.
realloc
Resizes an allocation, possibly moving it.
free
Returns heap memory. Every `malloc` needs exactly one `free`.
Undefined Behavior
Operations the standard gives no meaning — the compiler may assume they never happen.
Stack vs Heap
Automatic local variables live on the stack (fast, limited, freed on return); `malloc` memory lives on the heap (flexible, manual).
Alignment and Padding
CPUs prefer data at addresses that are multiples of its size, so compilers add padding inside structs.
Strict Aliasing
The compiler assumes pointers of unrelated types don't point to the same object.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.