Edit

Share via


Warning C6331

Invalid parameter: passing MEM_RELEASE and MEM_DECOMMIT in conjunction to *function* is not allowed. This results in the failure of this call

This message indicates that an invalid parameter is passed to VirtualFree or VirtualFreeEx. VirtualFree and VirtualFreeEx both reject the flags (MEM_RELEASE | MEM_DECOMMIT) in combination. Therefore, the values MEM_DECOMMIT and MEM_RELEASE may not be used together in the same call.

Remarks

It's not required for decommit and release to occur as independent steps. Releasing committed memory will decommit the pages as well. Also, ensure the return value of this function isn't ignored.

Code analysis name: VirtualFreeInvalidParam1

Example

The following sample code generates warning C6331:

#include <windows.h>
#define PAGELIMIT 80

DWORD dwPages = 0;  // count of pages
DWORD dwPageSize;   // page size

VOID fd( VOID )
{
  LPVOID lpvBase;            // base address of the test memory
  BOOL bSuccess;
  SYSTEM_INFO sSysInfo;      // system information

  GetSystemInfo( &sSysInfo );
  dwPageSize = sSysInfo.dwPageSize;

  // Reserve pages in the process's virtual address space
  lpvBase = VirtualAlloc (
                       NULL,                 // system selects address
                       PAGELIMIT*dwPageSize, // size of allocation
                       MEM_RESERVE,
                       PAGE_NOACCESS );
  if (lpvBase)
  {
    // code to access memory
  }
  else
  {
    return;
  }
  bSuccess = VirtualFree(lpvBase,
                0,
                MEM_DECOMMIT | MEM_RELEASE); // warning
  // code...
}

To correct this warning, don't pass MEM_DECOMMIT to the VirtualFree call, as shown in the following code:

#include <windows.h>
#define PAGELIMIT 80

DWORD dwPages = 0;  // count of pages
DWORD dwPageSize;   // page size

VOID f( VOID )
{
  LPVOID lpvBase;            // base address of the test memory
  BOOL bSuccess;
  SYSTEM_INFO sSysInfo;      // system information

  GetSystemInfo( &sSysInfo );
  dwPageSize = sSysInfo.dwPageSize;

  // Reserve pages in the process's virtual address space
  lpvBase = VirtualAlloc (
                       NULL,                 // system selects address
                       PAGELIMIT*dwPageSize, // size of allocation
                       MEM_RESERVE,
                       PAGE_NOACCESS );
  if (lpvBase)
  {
    // code to access memory
  }
  else
  {
    return;
  }
  bSuccess = VirtualFree(lpvBase, 0, MEM_RELEASE);
  // code...
}

The use of malloc and free (and related dynamic memory allocation APIs) has many pitfalls in terms of memory leaks and exceptions. 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.

See also

VirtualAlloc Method
VirtualFree Method