Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixed MEM36-CPP to MEM44-CPP names in Risk Assessment

...

In this non-compliant code example, the resources associated with the object pointed to by pst are not recovered in the event that processItem throws an exception, thereby potentially causing a resource leak.

Code Block
bgColor#FFcccc

while (moreToDo) {
  SomeType *pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    throw;
  }
  delete pst;
}

...

In this code, the exception handler recovers the resources associated with the object pointed to by pst.

Code Block
bgColor#ccccff

while (moreToDo) {
  SomeType *pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    delete pst;
    throw;
  }
  delete pst;
}

...

A better approach would be to employ RAII. This forces every object to 'clean up after itself' in the face of abnormal behavior, preventing the programmer from having to do so. A judicious unique_ptr would free the resource whether an error occurs or not.

Code Block
bgColor#ccccff

while (moreToDo) {
  std::unique_ptr<SomeType> pst = new SomeType();
  try {
    pst->processItem();
  }
  catch (...) {
    // deal with exception
    throw; // pst automatically freed
  }
  // pst automatically freed
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

RES38 MEM44-C CPP

1 (low)

2 (probable)

1 (high)

P2

L3

...