MiddleDebuggingCommonNot answered yet
Why does this leak when doWork throws?
This function frees its buffer, yet a leak detector flags it.
void process() {
int* buf = new int[1000];
doWork(buf); // may throw
delete[] buf;
}
Find and fix the bug.
If doWork throws, delete[] buf is skipped during stack unwinding, so the buffer leaks — manual new/delete is not exception-safe. Fix with RAII: std::vector<int> buf(1000); or auto buf = std::make_unique<int[]>(1000);, freed automatically while unwinding.
- ✗Assuming the OS reclaims leaked heap on exception within a running process
- ✗Thinking manual new/delete is exception-safe
- ✗Catching and swallowing the exception instead of using RAII
- →What exception-safety guarantee does the RAII version give this function?
- →Why does stack unwinding run destructors but not skipped
deletestatements?