A memory leak occurs when dynamically allocated storage is not released after it is no longer accessible or needed. A leak that seems harmless at program exit can become significant when repeated in a long-running program. section 6.3
In C++, a missing release is not the only cause. Cleanup can also be skipped when an object is destroyed incorrectly, or when assignment replaces a pointer without first managing the resource it already owns. section 8.8 section 7.6
Listing 6.5 Using malloc and free in an undisciplined manner
struct Buffer {
char* str;
Buffer(int size) : str(new char[size+1]) { str[0] = '\0'; }
~Buffer() { free(str); }
};
int main() {
double* val = (double*)malloc(sizeof(int)); #1
std::cout << val << '\n';
Buffer* buf = (Buffer*)malloc(sizeof(Buffer)); #2
std::cout << buf->str << ", size " << strlen(buf->str) << '\n';
free(buf);
return 0;
}
The allocation for val has no matching free. The Buffer allocation has additional problems: malloc does not call its constructor, and free does not call its destructor. The destructor also incorrectly pairs new[] with free. section 6.3
Use matching allocation and deallocation operations: new with delete, and new[] with delete[]. Construct objects so their destructors can release owned resources. RAII pairs resource acquisition with cleanup; smart pointers can also reduce leaks. Simply switching to new is not enough if a pointer is never deleted. section 6.3 section 2.0
Listing 8.15 Base class without a virtual destructor
class Point {
private:
double x;
double y;
public:
Point(double x, double y) : x(x), y(y) {}
};
class Shape {
private:
Point* location;
public:
Shape(double x, double y) : location(new Point(x, y)) {}
~Shape() { delete location; std::cout << "~Shape\n"; } #1
virtual double area() const = 0; #2
};
class Square : public Shape {
private:
double* side;
public:
Square(double side, double x, double y) : Shape(x, y),
side(new double(side)) {}
~Square() { delete side; std::cout << "~Square\n"; }
double area() const { return *side * *side; } // looks weird
};
int main() {
Shape* s = new Square(2.5, 0, 0); // place at origin
std::cout << s->area() << '\n';
delete s; #3
return 0;
}
Square owns a dynamically allocated side, but Shape has no virtual destructor. Deleting the Square through a Shape pointer has undefined behavior; the observed run calls only the base destructor and leaks side. section 8.8
Give a polymorphic base class a virtual destructor so deletion through a base pointer can run derived cleanup. For classes that own dynamic resources, also consider copy construction and copy assignment: assignment must account for the target's existing resource as well as self-assignment. section 8.8 section 7.6





