It is important that resources are reclaimed when exceptions are thrown. Throwing an exception may result in cleanup code being bypassed. As a result, it is the responsibility of the exception handler to properly clean up. This may be problematic if the exception is to be caught in a different function or module. Instead, it is preferable if resources are reclaimed automatically when objects go out of scope.
Non-Compliant Code Example
while (moreToDo) { SomeType *pst = getNextItem(); try { pst->processItem(); } catch (...) { // deal with exception throw; } delete pst; }
The code above does not recover the resources associated with the object pointed to by pst
in the event that processItem
throws an exception, thereby potentially causing a resource leak.
Compliant Solution
while (moreToDo) { SomeType *pst = getNextItem(); try { pst->processItem(); } catch (...) { // deal with exception delete pst; throw; } delete pst; }
In this code, the exception handler recovers the resources associated with the object pointed to by pst
.
It might be better to replace the pointer pst
with an auto_ptr
that automatically cleans up itself.
Priority: P2 Level: L3
Memory and other resource leaks will eventually cause a program to crash. If an attacker can provoke repeated resource leaks by forcing an exception to be thrown through the submission of suitably crafted data, then the attacker can mount a denial-of-service attack.
Component |
Value |
---|---|
Severity |
1 (low) |
Likelihood |
2 (probable) |
Remediation cost |
1 (high) |
References
- Meyers 96 Item 9: "Use destructors to prevent resource leaks".