chiyer
chiyer

Reputation: 787

how to get the region size that is reserved in the initial allocation call to VirtualAlloc

in msdn doc of VirtualFree

BOOL WINAPI VirtualFree(
  _In_  LPVOID lpAddress,
  _In_  SIZE_T dwSize,
  _In_  DWORD dwFreeType
);

dwSize [in] The size of the region of memory to be freed, in bytes.

If the dwFreeType parameter is MEM_RELEASE, this parameter must be 0 (zero). The function frees the entire region that is reserved in the initial allocation call to VirtualAlloc.

seem that system can be obtained the entire region size through the address

My question is : how can I do that (to obtained the entire region size through the address)

PS : VirtualQuery API can not do that

void* p = VirtualAlloc(null, static_cast<SIZE_T>(_K * 128), MEM_RESERVE, PAGE_NOACCESS);
p = VirtualAlloc(p, _K * 64, MEM_COMMIT, PAGE_READWRITE);
MEMORY_BASIC_INFORMATION im;
VirtualQuery(p, &im, sizeof(im));

the im.RegionSize is the size of MEM_COMMIT, not the entire region size of first call VirtualAlloc

Upvotes: 3

Views: 2023

Answers (2)

Remus Rusanu
Remus Rusanu

Reputation: 294227

MEMORY_BASIC_INFORMATION:

AllocationBase A pointer to the base address of a range of pages allocated by the VirtualAlloc function. The page pointed to by the BaseAddress member is contained within this allocation range.

Keep querying until you fall off the edge:

void* p = VirtualAlloc(NULL, static_cast<SIZE_T>(_K * 128), MEM_RESERVE, PAGE_NOACCESS);
void* p2 = VirtualAlloc(p, _K * 64, MEM_COMMIT, PAGE_READWRITE);
MEMORY_BASIC_INFORMATION im;
VirtualQuery(p2, &im, sizeof(im));
while (im.AllocationBase == p)
{
    p2 = (unsigned char *)p2 + im.RegionSize;
    VirtualQuery(p2, &im, sizeof(im));
}

Upvotes: 4

user420442
user420442

Reputation:

It's information you have to keep track of yourself.

Reserving address space does just that - it reserves addresses. There's no concept of how large that space is, because you could reserve two chunks that happen to be adjacent to each other, and then commit a single block across both reserved spaces.

Upvotes: 0

Related Questions