A memory leak occurs when dynamically allocated storage is no longer usable but remains unreleased. Long-running programs can accumulate leaks, reducing stability and available resources. section 6.3 section 7.6
Common C++ mistakes create leaks or make resource ownership unreliable:
- Allocating with malloc and omitting the matching release leaves storage behind. section 6.3
- Calling free on an object allocated with new skips destruction; mixing new with free produces undefined behavior. section 6.3
- Deleting a derived object through a base pointer without a virtual destructor can leak derived resources. section 8.8
- Copy constructors and assignment operators that share unique pointers can cause ownership errors; assignment must replace existing resources safely. 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;
}
Compare the undisciplined allocation example with its corrected new/delete version to identify missing initialization, missing deletion, and mismatched release operations. section 6.3
Prefer ownership that pairs acquisition with release. Constructors should establish resource ownership, destructors should release it, and copy or move operations should preserve the ownership model. RAII and smart pointers reduce the opportunity for leaks, while a virtual destructor enables correct polymorphic cleanup. section 6.3 section 8.8 section 2.0 section 7.6




