如何通过一次 VirtualFree 调用删除多个相邻的虚拟内存分配?

How to delete several adjacent virtual memory allocations with one VirtualFree call?

下面只是一个简短的测试代码示例来说明我的问题:

SYSTEM_INFO si;
GetSystemInfo(&si);

//Go by allocation granularity to have a chance to reserve adjacent memory chunks
size_t szAlloc = si.dwAllocationGranularity;

//Try to alloc two adjacent memory chunks
BYTE* pp1 = (BYTE *)::VirtualAlloc(NULL, szAlloc, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ASSERT(pp1);
BYTE* pp2 = (BYTE *)::VirtualAlloc(pp1 + szAlloc, szAlloc, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ASSERT(pp2);

//We should be able to write between them
WORD ui = 0xAB;
BYTE* p = pp1 + szAlloc - sizeof(ui) / 2;
*(WORD*)p = ui;

//Release both at once
BOOL bb = ::VirtualFree(pp1, szAlloc + szAlloc, MEM_RELEASE);
int err = ::GetLastError();

如何一次调用释放两个内存块?或者将它们合并为一个块,如果不允许立即释放? (我问的原因是因为在我的实际代码中可能不止有 2 个相邻的块。)

PS。在上面的测试代码中 VirtualFree 失败,错误代码为 ERROR_INVALID_ADDRESS.

你不能做你想做的事。虽然我不确定您为什么要这样做 - 如果您需要释放多个分配,然后单独释放它们。

但是,我认为您可以通过保留一块大内存(通过 auto ptr = VirtualAlloc(nullptr, ..., MEM_RESERVE, ...); 部分地实现您想要的,然后在您想要通过 VirtualAlloc((uint_t*)ptr+offset, ..., MEM_COMMIT, ...);.

如果您这样做,那么您只需一次调用 vid VirtualFree(ptr, 0, MEM_RELEASE)

就可以释放整个大预留(包括您单独提交的所有部分)