< previous page page_147 next page >

Page 147
In line 14, the memory allocated in line 9 is returned to the free store by a call to delete. This frees the memory and disassociates the pointer from that memory. pHeap is now free to point to other memory. It is reassigned in 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 memory),it is a good idea to free this memory explicitly. If the program changes or is extended, it will be beneficial that this step was already taken care of.
Memory Leaks
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 pPointer and 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 pPointer to another area of memory. Line 4 places the value 84 in that area. The original areain which the value 72 is now heldis unavailable because the pointer to that area of memory has been reassigned. There is no way 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 pPointer is deletedand thus freedin 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 memory and to ensure that the memory is returned to the free store when you are done with it.

 
< previous page page_147 next page >

If you like this book, buy it!