The 2-hour pointer bug that finally made pointers click
What I worked on
Working through a small C exercise: writing a function that should modify an array in place through a pointer argument. Simple in theory. Took me two hours to get right.
What I learned
The core realization: a pointer variable itself lives at an address too. Passing a pointer by value means the function gets a copy of the address, which is fine for modifying what it points to, but if you want the function to change what the caller's pointer points to, you need a pointer to a pointer.
Problems / debugging
My function was supposed to reallocate memory and have the caller see the new pointer, but the caller kept seeing the old (freed) pointer. Classic mistake — I was passing int *arr instead of int **arr and reassigning the local copy, which never propagated back.
Fixed it by:
- Changing the parameter to
int **arr - Dereferencing once to assign:
*arr = realloc(*arr, newSize * sizeof(int)); - Updating every access inside the function from
arr[i]to(*arr)[i]
Decisions
I'm going to deliberately do a handful of "pointer to pointer" exercises this week instead of moving on immediately, because I don't want this to be a thing I "sort of get" — I want it automatic before I touch embedded C where this pattern shows up constantly (e.g. HAL functions that return status via pointer params).
Things I didn't fully understand
Function pointers are still fuzzy. I understand the syntax mechanically but haven't built the intuition for when I'd actually reach for one yet.
Experiments
Drew the memory layout by hand on paper — boxes for stack frames, arrows for what points where. Genuinely more useful than anything I read online. Might start doing this by default for pointer-heavy code.
Tomorrow's plan
Write a tiny linked list implementation from scratch (insert, delete, traverse) as the next rung up from this.