Example Code for Leak #3
// The following code demonstrates the
// memory leakage problems associated
// with deleting a dynamically allocated
// array of Point objects.
#include <iostream.h>
class Point {
int x, y;
char* color;
public:
Point(int=0, int=0, char*=''Red'');
~Point();
};
{
x = new_x;
y = new_y;
color = new char[strlen(col)+1];
strcpy(color, col);
}
Point::~Point()
{
delete color;
cout << ''In the destructor\n'';
}
Point::Point(int new_x, int new_y, char* col)
main()
{
Point *p = new Point[5];
// Note the missing square brackets. This
// statement is identical to ''delete[1] p;''.
// It will call the destructor once with
// the address of &p[0] as an argument. The
// color string of the first Point object is
// put back on the heap followed by the
// memory occupied by the five Point objects.
// The memory leaked is the color strings for
// Points two through five (indices 1 to 4).
delete p;
// The correct statement is :
// delete[] p; or delete[5] p;
}
|