< Free Open Study > |
Example Code for Leak #4#include <iostream. h> class Point { int x, y; char* color; Point(int=0, int=0, char*=''Red''); ~Point(); }; Point::Point(int new_x, int new_y, char* col) { x = new_x; y = new_y; color = new char[strlen(col)+1]; strcpy(color, col); } Point::~Point() { delete color; } main() { // The following line of code dynamically // allocates an array of 10 pointers to // Point objects (not the objects themselves). Point **p = new Point*[10]; int i; // The loop below allocates one Point object // for each of the Point pointers. for (i=0; i<10; i++) { p[i] = new Point(i, i, ''Green''); } // The following statement does not clean up // the individual points, just their pointers. It // results in the leakage of memory // (10*sizeof(Point) + 60 bytes of space). // Note: The 60 bytes are incurred for the // storage of the string ''Green'' in each of the // 10 objects. delete[]p; // or delete[10] p; // The correct code is as follows: /* for (i=0; i < 10; i++) { delete p[i]; } delete p; */ } |
< Free Open Study > |