C6211

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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 throw an exception. The analyzer checks for this condition only when the _Analysis_mode_(_Analysis_local_leak_checks_) SAL annotation is specified. By default, this annotation is specified for Windows kernel mode (driver) code. For more information about SAL annotations, see Using SAL Annotations to Reduce C/C++ Code Defects.

Example

The following code generates this warning because an exception could be thrown during the second allocation and thereby leak the first allocation, or an exception could be thrown somewhere in the code that's represented by the "code ..." comment and thereby leak both allocations.

// cl.exe /analyze /c /EHsc /nologo /W4   
#include <sal.h>  
  
_Analysis_mode_(_Analysis_local_leak_checks_)   
void f( )  
{  
    char *p1 = new char[10];  
    char *p2 = new char[10];  
  
    // code ...  
  
    delete[] p2;  
    delete[] p1;  
}  
  

To use the same allocation methods and correct this problem, add an exception handler:

// cl.exe /analyze /c /EHsc /nologo /W4  
#include <sal.h>  
#include <new>  
#include <iostream>  
using namespace std;  
  
_Analysis_mode_(_Analysis_local_leak_checks_)   
  
void f()  
{  
    char *p1 = nullptr;   
    char *p2 = nullptr;  
  
    try  
    {  
        p1 = new char[10];  
        p2 = new char[10];  
  
        // code ...  
  
        delete [] p2;  
        delete [] p1;  
    }  
    catch (const bad_alloc& ba)  
    {  
        cout << ba.what() << endl;  
        delete [] p2;  
        delete [] p1;  
    }  
    // code ...  
}  
  

To avoid these kinds of potential leaks altogether, use the mechanisms that are provided by the C++ Standard Template Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers and C++ Standard Library.

// cl.exe /analyze /c /EHsc /nologo /W4  
#include <sal.h>  
#include <vector>  
#include <memory>  
  
using namespace std;  
  
_Analysis_mode_(_Analysis_local_leak_checks_)   
  
void f( )  
{  
    // use 10-element vectors in place of char[10]  
    vector<char> v1;  
    vector<char> v2;  
  
    for (int i=0; i<10; ++i) {  
        v1.push_back('a');  
        v2.push_back('b');  
    }  
    // code ...  
  
    // use unique_ptr if you still want char[10]  
    unique_ptr<char[]> a1(new char[10]);  
    unique_ptr<char[]> a2(new char[10]);  
  
    // code ...  
  
    // No need for delete; vector and unique_ptr   
    // clean up when out of scope.  
}  
  

See Also

C++ Exception Handling