Quick Answer
Using new/delete with exception safety.
Understanding the Issue
Manual memory management requires careful pairing of allocations and deallocations. Prefer RAII wrappers for automatic cleanup.
The Problem
This code demonstrates the issue:
Cpp
Error
// Problem: Memory leak
void process() {
int* buf = new int[1024];
if(error) return; // Leak
delete[] buf;
}
The Solution
Here's the corrected code:
Cpp
Fixed
// Solution 1: Smart pointer
void safe() {
auto buf = make_unique<int[]>(1024);
// Automatic deletion
}
// Solution 2: Custom deleter
struct Deleter {
void operator()(int* p) { delete[] p; }
};
unique_ptr<int[], Deleter> ptr(new int[1024]);
Key Takeaways
Never use raw new/delete in modern C++.