C6279

warning C6279: <variable> is allocated with scalar new, deleted with array delete []

This warning appears only in C++ code and indicates that the calling function has inconsistently allocated memory with the scalar new operator, but freed it with the array delete [] operator. If memory is allocated with scalar new, it should typically be freed with scalar delete.

There are at least three reasons that this is likely to cause problems:

  • The constructors for the individual objects in the array are not invoked, although the destructors are.

  • If global (or class-specific) operator new and operator delete are not compatible with operator new[] and operator delete[], unexpected results are likely to occur.

The exact ramifications of this defect are difficult to predict. It might cause random behavior or crashes due to usage of uninitialized memory because constructors are not invoked. Or, it might cause memory allocations and crashes in situations where operators have been overridden. In rare cases, the mismatch might be unimportant. Analysis tool does not currently distinguish between these situations.

Example

The following code generates this warning:

class A
{
  // members
};

void f ( )
{
  A *pA = new A;
  //code ...
  delete[] pA;
}

To correct this warning, use the following code:

void f( )
{
  A *pA = new A;
  //code ...
  delete pA;
}

To avoid these kinds of allocation problems 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 C++ Standard Library Reference.

See Also

Reference

C6014