A long time ago I used to program in C for school. I remember something that I really hated about C: unassigned pointers do not point to NULL.
I asked many people in
When you declare a (pointer) variable at the beginning of the function, the compiler will do one of two things: set aside a register to use as that variable, or allocate space on the stack for it. For most processors, allocating the memory for all local variables in the stack is done with one instruction; it figures out how much memory all the local vars will need, and pulls down (or pushes up, on some processors) the stack pointer by that much. Whatever is already in that memory at the time is not changed unless you explicitely change it.
The pointer is not "set" to a "random" value. Before allocation, the stack memory below the stack pointer (SP) contains whatever is there from earlier use:
.
.
SP ---> 45
ff
04
f9
44
23
01
40
.
.
.
After it allocates memory for a local pointer, the only thing that has changed is the stack pointer:
.
.
45
ff |
04 | allocated memory for pointer.
f9 |
SP ---> 44 |
23
01
40
.
.
.
This allows the compiler to allocate all local vars in one instruction that moves the stack pointer down the stack (and free them all in one instruction, by moving the stack pointer back up), but forces you to initialize them yourself, if you need to do that.
In C99, you can mix code and declarations, so you can postpone your declaration in the code until you are able to initialize it. This will allow you to avoid having to set it to NULL.