How it works...

The preceding code does what is shown in the diagram that follows:

  1. The first line creates an int * pointer variable, i, which starts as a dangling pointer referring to a segment of memory that probably won't be valid for your program to reference.
  2. In the second step of the diagram, we use a malloc() call to initialize the variable i to point to a segment of memory precisely the size of an int variable, which will be valid for your program to refer to.
  3. We then initialize the contents of that memory segment to the value 0 using the command *i = 0;. Refer to the following diagram:
Note the difference between the assignment to a pointer variable ( i = ), which tells the pointer which memory address to refer to, and the assignment to what it is inside the memory address that the pointer variable refers to ( *i = ).

When the memory in the variable i needs to be released back to the system, we do so using a free() de-allocation call, as shown in the following diagram. i is then assigned to point to the memory address, 0, shown in this diagram by the electrical grounding symbol reference, :

The reason we set the variable i to point to the NULL reference is to make it clear that the variable i does not refer to a valid segment of memory.