VirtualAlloc Function
LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect);
Description
The VirtualAlloc
function reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. It can also optionally place the new region within a specified memory range, specify whether pages that are opened with write access can be written to, and control the access permissions of the pages.
Syntax
LPVOID VirtualAlloc(
[in, optional] LPVOID lpAddress,
[in] SIZE_T dwSize,
[in] DWORD flAllocationType,
[in] DWORD flProtect
);
Parameters
Parameter | Description |
---|---|
lpAddress |
[in, optional] A pointer to the base address of the region of pages to be allocated. If this parameter is |
dwSize |
[in] The size, in bytes, of the region of pages to be allocated. If If |
flAllocationType |
[in] The type of memory allocation. This parameter can be one of the following values:
You can also combine |
flProtect |
[in] The memory protection for the region of pages to be allocated. This parameter can be one of the following values:
You can also use the |
Return Value
If the function succeeds, the return value is the base address of the allocated region of pages. If the function fails, the return value is NULL
. To get extended error information, call GetLastError
.
Remarks
VirtualAlloc
is used to reserve or commit a region of memory pages.- For
MEM_RESERVE
,flProtect
can bePAGE_NOACCESS
. - For
MEM_COMMIT
,flProtect
can be any of thePAGE_XXX
values exceptPAGE_NOACCESS
. - When committing pages, the memory type specified by
flAllocationType
must be compatible with the memory type of the region already specified bylpAddress
. - If
lpAddress
is notNULL
, the starting address of the block of pages to be allocated is within the range of addresses specified bylpAddress
when the region was created by a previous call toVirtualAlloc
. - To decommit a region of pages, call
VirtualFree
. - If the system cannot commit the region of memory or if
lpAddress
is invalid, the function fails.
Example
The following code example allocates a region of memory and then commits it.
// Allocate 4K of memory
LPVOID lpMsgBuf = VirtualAlloc(
NULL, // System chooses the address
4096, // Size of allocation
MEM_RESERVE | MEM_COMMIT, // Reserve and commit
PAGE_READWRITE // Read-write access
);
if (lpMsgBuf == NULL)
{
// Handle error
printf("VirtualAlloc failed: %d\n", GetLastError());
return 1;
}
// Use the allocated memory...
// Free the allocated memory
if (!VirtualFree(lpMsgBuf, 0, MEM_RELEASE))
{
// Handle error
printf("VirtualFree failed: %d\n", GetLastError());
return 1;
}