VirtualAlloc 对齐与分配大小一致吗? [英] Is VirtualAlloc alignment consistent with size of allocation?

查看:19
本文介绍了VirtualAlloc 对齐与分配大小一致吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 VirtualAlloc API 分配和提交一个虚拟内存区域时,页面边界大小为 2 次方,例如:

When using the VirtualAlloc API to allocate and commit a region of virtual memory with a power of two size of the page boundary such as:

void* address = VirtualAlloc(0, 0x10000, MEM_COMMIT, PAGE_READWRITE); // Get 64KB

address 似乎总是以 64KB 对齐,而不仅仅是页面边界,在我的例子中是 4KB.

The address seems to always be in 64KB alignment, not just the page boundary, which in my case is 4KB.

问题是:这种对齐方式是否可靠和规定,还是只是巧合?文档 声明它是有保证的位于页面边界上,但没有解决我所看到的行为.我问是因为我以后想获取一个任意指针(由使用此块的池分配器提供)并通过类似于以下内容的方法确定它属于哪个 64KB 块:

The question is: Is this alignment reliable and prescribed, or is it just coincidence? The docs state that it is guaranteed to be on a page boundary, but does not address the behavior I'm seeing. I ask because I'd later like to take an arbitrary pointer (provided by a pool allocator that uses this chunk) and determine which 64KB chunk it belongs to by something similar to:

void* chunk = (void*)((uintptr_t)ptr & 0xFFFF0000);

推荐答案

VirtualAlloc 描述了 2 个场景的行为:1)保留内存和 2)提交内存:

The documentation for VirtualAlloc describes the behavior for 2 scenarios: 1) Reserving memory and 2) Committing memory:

如果内存正在保留,则指定的地址将向下舍入到最接近的分配粒度的倍数.

If the memory is being reserved, the specified address is rounded down to the nearest multiple of the allocation granularity.

如果内存已被保留并且正在提交,则地址将向下舍入到下一个页面边界.

If the memory is already reserved and is being committed, the address is rounded down to the next page boundary.

换句话说,内存以分配粒度的倍数分配(保留)并以页面大小的倍数提交.如果您在单个步骤中保留和提交内存,它将以分配粒度的倍数对齐.当提交已经保留的内存时,它将在页面边界处对齐.

In other words, memory is allocated (reserved) in multiples of the allocation granularity and committed in multiples of a page size. If you are reserving and committing memory in a single step, it will be be aligned at a multiple of the allocation granularity. When committing already reserved memory it will be aligned at a page boundary.

要查询系统的页面大小和分配粒度,请调用 GetSystemInfo.SYSTEM_INFO 结构的 dwPageSizedwAllocationGranularity 将分别保存页面大小和分配粒度.

To query a system's page size and allocation granularity, call GetSystemInfo. The SYSTEM_INFO structure's dwPageSize and dwAllocationGranularity will hold the page size and allocation granularity, respectively.

这篇关于VirtualAlloc 对齐与分配大小一致吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆