Understanding Pointers 235
8
Putting Memory Back: The deleteKeyword ................................................
When you are finished with an area of memory, you must free it back to the system. You
do this by calling deleteon the pointer. deletereturns the memory to the free store.
It is critical to remember that memory allocated with newis not freed automatically. If a
pointer variable is pointing to memory on the free store and the pointer goes out of
scope, the memory is not automatically returned to the free store. Rather, it is considered
allocated and because the pointer is no longer available, you can no longer access the
memory. This happens, for instance, if a pointer is a local variable. When the function in
which that pointer is declared returns, that pointer goes out of scope and is lost. The
memory allocated with newis not freed—instead, it becomes unavailable.
This situation is called a memory leak. It’s called a memory leak because that memory
can’t be recovered until the program ends. It is as though the memory has leaked out of
your computer.
To prevent memory leaks, you should restore any memory you allocate back to the free
store. You do this by using the keyword delete. For example:
delete pPointer;
When you delete the pointer, you are really freeing up the memory whose address is
stored in the pointer. You are saying, “Return to the free store the memory that this
pointer points to.” The pointer is still a pointer, and it can be reassigned. Listing 8.4
demonstrates allocating a variable on the heap, using that variable, and deleting it.
Most commonly, you will allocate items from the heap in a constructor, and deallocate
them in the destructor. In other cases, you will initialize pointers in the constructor, allo-
cate memory for those pointers as the object is used, and, in the destructor, test the point-
ers for null and deallocate them if they are not null.
If newcannot create memory on the free store (memory is, after all, a limited
resource), it throws an exception (see Day 20, “Handling Errors and
Exceptions”).
NOTE
When you call deleteon a pointer, the memory it points to is freed. Calling
deleteon that pointer again crashes your program! When you delete a
pointer, set it to zero (null). Calling deleteon a null pointer is guaranteed
to be safe. For example:
CAUTION