CodeQL documentation

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

  • © GitHub, Inc.
  • Terms
  • Privacy