[ fromfile: ptrpathology2.xml id: ptrpathologystorage ]
One of the richest sources of runtime errors is the production of memory leaks.
A memory leak is produced when a program causes memory to be allocated and then loses track of that memory so that it can neither be accessed nor deleted.
The operators new
and delete
give the C++ programmer increased power and increased responsibility.
Following is some sample code that illustrates a memory leak.
int* ip = new int; // allocate space for an int int* jp = new int(13); // allocate and initialize cout << ip << '\t' << jp << endl;
jp = new int(3); // reassign the pointer - MEMORY LEAK!!
After executing the following line of code, memory looks like Figure 21.2.
In Example 21.3, we delete the pointer jp
twice.
Example 21.3. src/pointers/pathology/pathologydemo1.cpp
#include <iostream> using namespace std; int main() { int* jp = new int(13); cout << jp << '\t' << *jp << endl; delete jp; delete jp; jp = new int(3); cout << jp << '\t' << *jp << endl; jp = new int(10); cout << jp << '\t' << *jp << endl; int* kp = new int(17); cout << kp << '\t' << *kp << endl; return 0; } Output: OOP> g++ pathologydemo1.cpp OOP> ./a.out 0x8049e08 13 0x8049e08 3 0x8049e08 10 Segmentation fault OOP>
The second deletion is a serious error but the compiler did not catch it.
That error corrupted the heap, made any further memory allocation impossible, and made the behavior of the program beyond that point undefined.
For example, notice that when we attempted to produce a memory leak by reassigning the pointer jp
we did not get any new memory.
When we attempted to introduce another pointer variable we got a segmentation fault.
This is all undefined behavior and may be different on another platform or with another compiler.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |