21.2. Further Pointer Pathology with Heap Memory

[ fromfile: ptrpathology2.xml id: ptrpathologystorage ]

 int* ip = new int;        // allocate space for an int
 int* jp = new int(13);    // allocate and initialize
 cout << ip  << '\t'  <<  jp  << endl;
 

Figure 21.1.  Initial Values of Memory

Initial Values of Memory

 
  • After executing the following line of code, memory looks like Figure 21.2.

jp = new int(3); // reassign the pointer - MEMORY LEAK!!

Figure 21.2.  Memory After Leak

Memory After Leak

Example 21.3. src/pointers/pathology/pathologydemo1.cpp

#include <iostream>
using namespace std;

int main() {
    int* jp = new int(13); 1
    cout << jp << '\t' << *jp << endl;
    delete jp;
    delete jp;             2
    jp = new int(3);       3
    cout << jp << '\t' << *jp << endl;
    jp = new int(10);      4
    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>


1

Allocate and initialize.

2

Error: pointer already deleted.

3

Reassign the pointer, memory leak.

4

Reassign the pointer, memory leak.