Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Move uninitialized delete here from MEM51-CPP

...

Code Block
bgColor#ccccff
langcpp
class S {
  int c;
 
public:
  S() : c(0) {}
  int f(int i) const { return i + c; }
};
 
void f() {
  S s;
  int i = s.f(10);
}

Noncompliant Code Example (Uninitialized delete)

In this noncompliant code example, two allocations are attempted within the same try block, and if either fails, the catch handler attempts to free resources that have been allocated. However, because the pointer variables have not been initialized to a known value, a failure to allocate memory for i1 will result in reading the uninitialized i2, resulting in undefined behavior.

Code Block
bgColor#FFcccc
langcpp
#include <new>
 
void f() {
  int *i1, *i2;
  try {
    i1 = new int;
    i2 = new int;
  } catch (std::bad_alloc &) {
    delete i1;
    delete i2;
  }
}

Compliant Solution (Uninitialized delete)

This compliant solution initializes both pointer values to nullptr.

Code Block
bgColor#ccccff
langcpp
#include <new>
 
void f() {
  int *i1 = nullptr, *i2 = nullptr;
  try {
    i1 = new int;
    i2 = new int;
  } catch (std::bad_alloc &) {
    delete i1;
    delete i2;
  }
}

Risk Assessment

Reading uninitialized variables is undefined behavior and can result in unexpected program behavior. In some cases, these security flaws may allow the execution of arbitrary code.

...