Until you gain experience with the new and delete operators, it is important to pronounce the statement
delete intPtr;
accurately. Instead of saying Delete intPtr, it is better to say Delete the variable pointed to by intPtr. The delete operation does not delete the pointer; it deletes the pointed-to variable.
When using the delete operator, you should keep two rules in mind.
1. Applying delete to the null pointer does no harm; the operation simply has no effect.
2. Excepting rule 1, the delete operator must only be applied to a pointer value that was obtained previously from the new operator.
The second rule is important to remember. If you apply delete to an arbitrary memory address that is not in the free store, the result is undefined and could prove to be very unpleasant.
Finally, remember that a major reason for using dynamic data is to economize on memory space. The new operator lets you create variables only as they are needed. When you are finished using a dynamic variable, you should delete it. It is counterproductive to keep dynamic variables when they are no longer neededa situation known as a memory leak. If this is done too often, you may run out of memory.
Memory Leak The loss of available memory space that occurs when dynamic data is allocated but never deallocated.
Let's look at another example of using dynamic data.
int* ptr1 = new int; // Create a dynamic variable
int* ptr2 = new int; // Create a dynamic variable
*ptr2 = 44; // Assign a value to a dynamic variable
*ptr1 = *ptr2; // Copy one dynamic variable to another
ptr1 = ptr2; // Copy one pointer to another
delete ptr2; // Destroy a dynamic variable
Here is a more detailed description of the effect of each statement:
int* ptr1 = new int;
Creates a pair of dynamic variables of type int and stores their locations into ptr1 and prt2.