← Pointers and MemoryC PROGRAMMING 1.2.G

Pointer Bugs, const, void*, volatile

Wild and dangling pointers, const combinations, void* casting rules, volatile basics.

StatusCollected
NotesChapter test: 5/5

Seven pieces rounding out the ways a pointer can go wrong, plus the qualifiers — const, void*, volatile — that show up on almost every function signature from here on.

Wild vs dangling

  • Wild pointer — never initialized to anything meaningful; holds garbage from the start.
  • Dangling pointer — was valid once, but points at memory that's since been freed or gone out of scope.

Dangling pointers are the more dangerous of the two, because the memory they point at often still looks fine for a while — the bug shows up later, somewhere that looks completely unrelated, which makes it much harder to trace back to the actual cause.

The const combinations

const int *p1;              /* pointer to a const int — can't change *p1, can reassign p1 */
int * const p2 = &x;        /* const pointer to int — can change *p2, can't reassign p2 */
const int * const p3 = &x;  /* both — can change neither */

Read it right to left from the *: const int * is "a pointer to a const int," int * const is "a const pointer to int." The position of const relative to the * is the entire difference.

void* and volatile

void * is C's generic pointer — it can point at anything, but can't be dereferenced directly and can't do pointer arithmetic until it's cast to a concrete type first. volatile tells the compiler a value can change outside the program's own control flow, so it can't cache it in a register or optimize away what looks like a redundant read — a first hint of why it matters for hardware registers, which is exactly where the next chapter goes.

Notes from readers

Comments — via GitHub