C6280

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 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.

Example

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 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(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