C6211

warning C6211: Leaking memory <pointer> due to an exception. Consider using a local catch block to clean up memory

This warning indicates that allocated memory is not being freed when an exception is thrown. The statement at the end of the path could potentially throw an exception.

Example

The following code generates this warning:

#include <new>
void f( )
{
  char *p1 = new char[10];
  char *p2 = new char[10];
  // code ...

  delete[] p1;
  delete[] p2;
}

To correct this warning, use exception handler as shown in the following code:

#include<new>
#include<iostream>
using namespace std;

void f( )
{
  char *p1=NULL; 
  char *p2=NULL;

  try
  {
    p1 = new char[10];
    p2 = new char[10];
    // code ...
    delete [] p1;
    delete [] p2;
  }
  catch (bad_alloc &ba)
  {
    cout << ba.what() << endl;
    if (NULL != p1)
      delete [] p1;
    if (NULL !=p2)
      delete [] p2;
  }
  // code ...
}

See Also

Reference

C++ Exception Handling