How pointers work
Store an address
The address operator & produces a pointer to an object. Declare the pointed-to type explicitly.
int value = 42;
int *pointer = &value;
printf("%d\n", *pointer);
Dereference only valid pointers
*pointer accesses the pointed-to object. Never dereference a null, uninitialized, dangling, misaligned, or one-past-the-end pointer.
int *pointer = NULL;
if (pointer != NULL) {
printf("%d\n", *pointer);
}
Follow lifetime rules
A pointer remains usable only while its target exists. Never return the address of an automatic local variable, and do not use allocated memory after free.
Clarify mutation and ownership
Use const int * for read-only access. For every pointer, know who owns the object, its bounds, whether null is allowed, and how long it remains alive.
- Initialize pointers before use
- Pass buffer capacities with buffer pointers
- Set an owning pointer to
NULLafter freeing when it remains in scope