Memory You Ask For
Everything so far lived on the stack. A function gets called, the program sets aside room for its variables, the function returns, the room is gone. Automatic. Fast. Very efficient. And it has one consequence that gets everybody exactly once.
int *broken(void) {
int n = 42;
return &n; // the address of a house that is about to be demolished
}The address is real when you return it. A moment later n is gone and those bytes belong to whoever shows up next. The pointer still has the number. The number means nothing anymore. That is a dangling pointer, and it is the first of the two ways pointers go bad.
When you need memory that outlives the function that made it, you go to the heap and you ask for it.
int *nums = malloc(4 * sizeof(int)); // room for four ints
if (nums == NULL) { /* the request failed. Deal with it. */ }
nums[0] = 10;
nums[1] = 20;
free(nums); // give it back
nums = NULL; // so nobody follows the old address by mistakemalloc finds a block the size you asked for and hands you the address. It is yours until you free it. It does not care what function made it or which one returned. The pointer is your only handle on that memory. That is what makes it powerful and that is what makes it dangerous. Same thing, like most powerful things.
Lose the pointer before you free, and the block is gone but still occupied. That is a leak. Use the pointer after you free, and you are touching memory that may already belong to somebody else. That is use after free, the second way pointers go bad. The two lines after free in the example are there to make the second mistake impossible. Cheap insurance. Take it.
I used to think stack versus heap was about speed. It is about time. Stack memory lives as long as the function. Heap memory lives as long as you say. Every decision about where to put something is a decision about how long it needs to exist and who is responsible for ending it. Ownership. It always comes back to ownership.
What I Carry Now
Six parts ago, asterisks and ampersands were noise. Here is the whole thing, compressed, the way it sits in my head now.
- Every variable has a value and an address.
&asks for the address. - A pointer is a variable that holds an address.
*follows it. - Functions get copies. Hand them an address and the copy still points home.
- An array is its first address.
a[i]is*(a + i), and the pointer’s type is the stride. - The stack ends with the function. The heap ends when you say. Every pointer bug is a question of who owns the memory and when it stops existing.
That is what I could not see in college. It was never eight ideas. It was two questions, where is it and what is there, asked about memory I had always been allowed to ignore. Stop ignoring it and the syntax turns out to be the easy part. The easiest part, actually. Nobody tells you that. Now somebody has.