< Previous | Contents | Next >

Using the delete Operator

Unlike storage for local variables on the stack, memory that youve allocated on the heap must be explicitly freed. When youre finished with memory that youve allocated with new, you should free it with delete. Thats what I do with the following line, which frees the memory on the heap that stored 10.

delete pHeap;

That memory is returned to the heap for future use. The data that was stored in it is no longer available. Next, I free some more memory, which frees the memory on the heap that stored 20.

delete pHeap2;

That memory is returned to the heap for future use, and the data that was stored in it is no longer available. Notice that theres no difference, as far as delete is concerned, regarding where in the program I allocated the memory on the heap that Im deleting.

Tric k

image

Because you need to free memory that you’ve allocated once you’re finished with it, a good rule of thumb is that every new should have a corresponding delete. In fact, some programmers write the delete statement just after writing the new statement whenever possible, so they don’t forget it.

image

Dynamically Allocating Memory 301


An important point to understand here is that the two previous statements free the memory on the heap, but they do not directly affect the local variables pHeap and pHeap2. This creates a potential problem because pHeap and pHeap2 now point to memory that has been returned to the heap, meaning that they point to memory that the computer can use in some other way at any given time. Pointers like this are called dangling pointers and they are quite dangerous. You should never attempt to dereference a dangling pointer. One way to deal with dangling pointers is to assign 0 to them, and thats what I do with the following lines, which reassign both dangling pointers so they no longer point to some memory to which they should not point.


pHeap = 0;

pHeap2 = 0;


Another good way to deal with a dangling pointer is to assign a valid memory address to it.


Tra p

image

Using delete on a dangling pointer can cause your program to crash. Be sure to set a dangling pointer to 0 or reassign it to point to a new, valid chunk of memory.

image