Share via


C6250

警告 C6250: 呼叫沒有 MEM_RELEASE 旗標的 <function> VirtualFree 可能會釋放記憶體,但不會釋放位址描述項 (VAD),因而導致位址空間遺漏

這項警告表示呼叫沒有 MEM_RELEASE 旗標的 VirtualFree 只會取消認可頁面,而不會加以釋放。 若要取消認可和釋放頁面,請在呼叫 VirtualFree 時使用 MEM_RELEASE 旗標。 如果已認可區域中的任何頁面,則函式會先取消認可,然後再加以釋放。 在這項作業之後,頁面會處於可用狀態。 當區域已保留時,如果您指定這個旗標,則 dwSize 必須為零,而 lpAddress 必須指向 VirtualAlloc 函式所傳回的基底位址 (Base Address)。 如果上述任一條件不符,則函式會失敗。

如果您的程式碼之後透過呼叫具有 MEM_RELEASE 旗標的 VirtualFree 來釋放位址空間,則可以忽略這項警告。

如需詳細資訊,請參閱 VirtualAlloc (英文) 和 VirtualFree (英文)。

範例

下列範例程式碼會產生這則警告:

#include <windows.h>
#include <stdio.h>
#define PAGELIMIT 80            

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

VOID f( )
{
  LPVOID lpvBase;            // base address of the test memory
  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);     
  //
  // code to access memory 
  // ...
 
  if (lpvBase != NULL)
  {
    if (VirtualFree( lpvBase, 0, MEM_DECOMMIT )) // decommit pages
      {
        puts ("MEM_DECOMMIT Succeeded");
      }
      else
      {
       puts("MEM_DECOMMIT failed");
      }
  }
  else
  {
    puts("lpvBase == NULL");
  }
}

若要更正這則警告,請使用下列範例程式碼:

#include <windows.h>
#include <stdio.h>
#define PAGELIMIT 80            

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

VOID f( )
{
  LPVOID lpvBase;            // base address of the test memory
  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);     
  //
  // code to access memory 
  // ...
 
  if (lpvBase != NULL)
  {
   if (VirtualFree(lpvBase, 0,MEM_RELEASE )) // decommit & release 
   {
     // code ...
   }
   else
   {
     puts("MEM_RELEASE failed");
   }
  }
  else 
  {
    puts("lpvBase == Null ");
    // code...
  }
}