Edit

Share via


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 isn't freed when an exception is thrown. The statement at the end of the path could throw an exception.

Remarks

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.

Code analysis name: MEMORY_LEAK_EXCEPTION

Example

The following code generates warning C6211 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 functions 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 Library (STL). These include shared_ptr, unique_ptr, and containers such as 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