Warning C6280

'variable-name' is allocated with 'function-name-1', but deleted with 'function-name-2'

This warning indicates that the calling function has inconsistently allocated memory by using a function from one family and freed it by using a function from another.

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.

For example, this warning would be produced if memory is allocated by using malloc but freed by using GlobalFree or delete. In the specific cases of mismatches between array new[] and scalar delete, more precise warnings are reported instead of this one.

Code analysis name: MEMORY_ALLOCATION_MISMATCH

Example

The following sample code generates this warning. pInt is allocated using calloc but is freed using the mismatched function delete:

// C6280a_warning.cpp
// cl.exe /analyze /c /EHsc /nologo /W4
#include <sal.h>
#include <stdlib.h>

_Analysis_mode_(_Analysis_local_leak_checks_)

void f(int arraySize)
{
    int *pInt = (int *)calloc(arraySize, sizeof (int));
    // code ...
    delete pInt;
}

The following code avoids this warning by using the deallocation function free, the match to calloc:

// C6280a_no_warning.cpp
// cl.exe /analyze /c /EHsc /nologo /W4
#include <sal.h>
#include <stdlib.h>

_Analysis_mode_(_Analysis_local_leak_checks_)

void f(int arraySize)
{
    int *pInt = (int *)calloc(arraySize, sizeof (int));
    // code ...
    free(pInt);
}

Different API definitions can use different heaps. For example, GlobalAlloc uses the system heap, and free uses the process heap. This issue is likely to cause memory corruptions and crashes.

These inconsistencies apply to the new/delete and malloc/free memory allocation mechanisms. To avoid these kinds of potential inconsistencies 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.

The following code avoids this problem entirely by using unique_ptr:

// C6280b_no_warning.cpp
// 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(int arraySize)
{
    // use unique_ptr instead of calloc/malloc/new
    unique_ptr<int[]> pInt(new int[arraySize]);

    // code ...

    // No need for free because unique_ptr
    // cleans up when out of scope.
}

See also

calloc
malloc
free
operator new
delete Operator
shared_ptr
unique_ptr
Smart pointers