I l @ ve RuBoard |
The operator new gets memory from the heap. To return the memory to the heap you use the operator delete . The general form of the delete operator is: delete pointer ; // Where pointer is a pointer to a simple object pointer = NULL; where pointer is a pointer previously allocated by new . If the new operator allocated an array, you must use the form: delete[] pointer ; // Where pointer is a pointer to an array pointer = NULL;
Strictly speaking, the line: pointer = NULL; is unnecessary. However, it is a good idea to "null out" pointers after they are deleted. That way, you don't try use a pointer to deleted memory, and you also help prevent any attempts to delete the same memory twice. The following is an example using new to get storage and delete to dispose of it: const DATA_SIZE = (16 * 1024); void copy( ) { char *data_ptr; // Pointer to large data buffer data_ptr = new char[DATA_SIZE]; // Get the buffer /* * Use the data buffer to copy a file */ delete[] data_ptr; data_ptr = NULL; } But what happens if we forget to free the memory? The buffer becomes dead. That is, the memory management system thinks it's being used, but no one is using it. (The technical term for this is a "memory leak.") If the delete statement is removed from the function copy , each successive call eats up another 16K of memory. The other problem that can occur is using memory that has been freed. When delete is used, the memory is returned to the memory pool and can be reused. Using a pointer after a delete call is similar to an array index out-of-bounds error. You are using memory that belongs to someone else. This can cause unexpected results or program crashes. |
I l @ ve RuBoard |