Export (0) Print
Expand All
Expand Minimize
This topic has not yet been rated - Rate this topic

C6280

warning C6280: <variable> is allocated with <function>, but deleted with <function>

This warning indicates that the calling function has inconsistently allocated memory by using a function from one memory allocation family and freed it by using a function from another memory allocation family. 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.

The following sample code generates this warning.

// 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;
}

To correct this warning, use this code:

// 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 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 Template Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers (Modern C++) and Standard C++ Library Reference.

// 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.
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.