Leaky catchΒΆ
ID: cpp/catch-missing-free
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- efficiency
- correctness
- exceptions
- external/cwe/cwe-401
Query suites:
- cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
Modern C++ code and frameworks should not throw or catch pointers. Older frameworks, such as Microsoftβs MFC, do throw and catch pointers. Said pointers will generally point to an exception object allocated on the heap, and therefore need to be freed when they are caught. Failure to free them will result in a memory leak.
RecommendationΒΆ
The catch
block should be augmented to delete the exception pointer.
ExampleΒΆ
void bad() {
try {
/* ... */
}
catch(CException* e) {
e->ReportError();
}
}
void good() {
try {
/* ... */
}
catch(CException* e) {
e->ReportError();
e->Delete();
}
}
ReferencesΒΆ
MSDN Library for MFC: Exceptions: Catching and Deleting Exceptions.
Common Weakness Enumeration: CWE-401.