Skip to main content

IAR Embedded Workbench for RX 5.20

COP-dealloc-dtor (C++ only)

In this section:
Synopsis

A class member has memory allocated in a constructor or an assignment operator, that is not released in the destructor.

Enabled by default

No

Severity/Certainty

High/Medium

highmedium.png
Full description

A class member has memory allocated to it in a constructor or assignment operator, that is not released in the class' destructor. This will most likely cause a memory leak when objects of this class are created and destroyed. Even if this is intentional (and the memory is released elsewhere) it is still dangerous, because it subverts the Resource Acquisition is Initialization convention, and consequently users of the class might not release the memory at all.

Coding standards
CWE 401

Improper Release of Memory Before Removing Last Reference ('Memory Leak')

Code examples

The following code example fails the check and will give a warning:

class MyClass{
  int *p;

public:
  MyClass() {
    p = 0;
  }

  MyClass(int i) {
    p = new int[i];
  }

  ~MyClass() {}  //p not deleted here
};

int main(void){
  MyClass *cp = new MyClass(5);
  delete cp;
}

The following code example passes the check and will not give a warning about this issue:

class MyClass{
  int *p;

public:
  MyClass(){
    p = 0;
  }

  MyClass(int i){
    p = new int[i];
  }

  ~MyClass(){
    if(p)
      delete[] p;  //OK - p is deleted here
  }
};

int main(void){
  MyClass *cp = new MyClass(5);
  delete cp;
}