Understanding Pointers 237
8
On line 14, the memory allocated on line 9 is returned to the free store by a call to
delete. This frees the memory and disassociates the pointer from that memory. pHeapis
now free to be used to point to other memory. It is reassigned on lines 15 and 16, and
line 17 prints the result. Line 18 restores that memory to the free store.
Although line 18 is redundant (the end of the program would have returned that mem-
ory), it is a good idea to free this memory explicitly. If the program changes or is
extended, having already taken care of this step is beneficial.
Another Look at Memory Leaks ........................................................................
Memory leaks are one of the most serious issues and complaints about pointers. You
have seen one way that memory leaks can occur. Another way you might inadvertently
create a memory leak is by reassigning your pointer before deleting the memory to
which it points. Consider this code fragment:
1: unsigned short int * pPointer = new unsigned short int;
2: *pPointer = 72;
3: pPointer = new unsigned short int;
4: *pPointer = 84;
Line 1 creates pPointerand assigns it the address of an area on the free store. Line 2
stores the value 72 in that area of memory. Line 3 reassigns pPointerto another area of
memory. Line 4 places the value 84 in that area. The original area—in which the value
72 is now held—is unavailable because the pointer to that area of memory has been reas-
signed. No way exists to access that original area of memory, nor is there any way to free
it before the program ends.
The code should have been written like this:
1: unsigned short int * pPointer = new unsigned short int;
2: *pPointer = 72;
3: delete pPointer;
4: pPointer = new unsigned short int;
5: *pPointer = 84;
Now, the memory originally pointed to by pPointeris deleted, and thus freed, on line 3.
For every time in your program that you call new, there should be a call to
delete. It is important to keep track of which pointer owns an area of mem-
ory and to ensure that the memory is returned to the free store when you
are done with it.
NOTE