Summary
The VirtualFree function releases, decommits, or both, a region of pages within the virtual address space of the calling process. It can also release extended storage.
Syntax
BOOL VirtualFree(
LPVOID lpAddress,
SIZE_T dwSize,
DWORD dwFreeType
);
Parameters
-
lpAddress [in]
The base address of the region of pages to be freed. This parameter must be the base address returned by the VirtualAlloc function. -
dwSize [in]
The size, in bytes, of the region of pages to be freed. This parameter must be 0. If lpAddress points to a memory page that was allocated by a call to VirtualAlloc, you must set dwSize to 0. -
dwFreeType [in]
The type of free operation. This parameter can be one of the following values:- MEM_RELEASE: Decommits the specified region of committed pages so that it is no longer accessible. It does not decommit the pages. The pages are in the process of being decommitted.
- MEM_DECOMMIT: Decommits the specified region of pages. A decommitted region can be reassigned to any other part of the process's address space. This is the only value that can be specified for dwFreeType.
Return Value
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
You must call VirtualFree to decommit and release a region of memory that was allocated by a call to the VirtualAlloc function. Failure to do so will result in a memory leak.
The dwSize parameter must be 0. The system determines the region of pages to be freed based on the lpAddress parameter.
The dwFreeType parameter specifies the type of free operation. MEM_RELEASE decommits the specified region of committed pages, making them inaccessible. MEM_DECOMMIT decommits the pages, allowing them to be reassigned. It is important to note that MEM_DECOMMIT is the only value that can be specified for dwFreeType.
Examples
The following example demonstrates how to decommit and release a memory region allocated with VirtualAlloc.
#include <windows.h>
#include <iostream>
int main() {
LPVOID pMem = nullptr;
SIZE_T size = 1024; // 1 KB
// Allocate memory
pMem = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (pMem == NULL) {
std::cerr << "VirtualAlloc failed. Error: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Memory allocated at: " << pMem << std::endl;
// ... Use the allocated memory ...
// Decommit and release the memory
if (VirtualFree(pMem, 0, MEM_RELEASE)) {
std::cout << "Memory successfully decommitted and released." << std::endl;
} else {
std::cerr << "VirtualFree failed. Error: " << GetLastError() << std::endl;
return 1;
}
return 0;
}
Requirements
Minimum supported client
Windows XP [desktop apps | UWP apps]
Minimum supported server
Windows Server 2003 [desktop apps | UWP apps]
Headerwinbase.h
LibraryKernel32.lib
DLLKernel32.dll