< Previous | Contents | Next >

Introducing the Heap Program

The Heap program demonstrates dynamic memory. The program dynamically allocates memory on the heap for an integer variable, assigns it a value, and then displays it. Next, the program calls a function that dynamically allocates memory on the heap for another integer variable, assigns it a value, and returns a pointer to it. The program takes the returned pointer, uses it to display the value, and then frees the allocated memory on the heap. Finally, the program contains two functions that demonstrate the misuse of dynamic memory. I dont call these functions, but I use them to illustrate what not to do with dynamic memory. Figure 9.3 shows the program.


image

Figure 9.3

The two int values are stored on the heap.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 9 folder; the filename is heap.cpp.

// Heap

// Demonstrates dynamically allocating memory

298 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby


#include <iostream> using namespace std;

int* intOnHeap(); //returns an int on the heap void leak1(); //creates a memory leak

void leak2(); //creates another memory leak


int main()

{

int* pHeap = new int;

*pHeap = 10;

cout << "*pHeap: " << *pHeap << "\n\n";


int* pHeap2 = intOnHeap();

cout << "*pHeap2: " << *pHeap2 << "\n\n";


cout << "Freeing memory pointed to by pHeap.\n\n"; delete pHeap;


cout << "Freeing memory pointed to by pHeap2.\n\n"; delete pHeap2;


//get rid of dangling pointers pHeap = 0;

pHeap2 = 0;


return 0;

}


int* intOnHeap()

{

int* pTemp = new int(20); return pTemp;

}


void leak1()

{

int* drip1 = new int(30);

}

Dynamically Allocating Memory 299



void leak2()

{

int* drip2 = new int(50); drip2 = new int(100); delete drip2;

}