HeapCreate和HeapAlloc混淆 [英] HeapCreate and HeapAlloc Confuse

查看:110
本文介绍了HeapCreate和HeapAlloc混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个有关动态内存管理的项目.我对HeapCreate和HeapAlloc函数感到困惑.

I am doing a project on dynamic memory management. I run into a confuse about the HeapCreate and HeapAlloc functions.

对于HeapCreate()函数,我们可以创建一个堆,该函数将返回一个HANDLE.我们可以初始化堆的大小.

For the HeapCreate() function, we can create a heap and the function will return a HANDLE. We can initialize the size of heap.

比方说winHandle = HeapCreate(0,2 * 1024,0);

Let's say winHandle = HeapCreate( 0, 2 * 1024, 0);

然后,我可以在该堆上分配HeapAlloc函数.但是我对堆的大小感到困惑.我尝试一个示例,在此堆上我两次调用HeapAlloc(winHandle,0,1024),所以总数将是2 *1024.但是我仍然可以多次调用HeapAlloc,而不会出错.

Then, I can the HeapAlloc function to allocate on this heap. But I am confuse about the size of the heap. I try an example, I call the HeapAlloc( winHandle, 0, 1024) twice on this heap, so the total will be 2 * 1024. But I can still call the HeapAlloc many times without run into an error.

假设我调用了HeapAlloc(winHandle,0,1024)3次.分配的总大小为3 *1024.它比堆大小2 * 1024大.但是没有错误.

Let's say I call the HeapAlloc( winHandle, 0, 1024) three times. The total size of allocation will be 3 * 1024. It is larger than the heap size 2 * 1024. But no error.

有人可以帮我回答这个问题吗?

Can anyone help me to answer this question?

谢谢

这是测试代码.

// create heap, and return a headle(id) for that heap
HANDLE winHandle = HeapCreate( 0, sizeof(Dog), sizeof(Dog) );


// allocate the heap header to that handle 
void* s = HeapAlloc( winHandle, 0, sizeof(Dog) );   
// check if the alloc is success or not
assert( 0 != s );
printf("%p \n", s);
// load the heap header data
Dog* heapHeader = new(s) Dog( 1, 2, 4);


// allocate the heap header to that handle 
void* ss = HeapAlloc( winHandle, 0, sizeof(Dog) );
// check if the alloc is success or not
assert( 0 != ss );
printf("%p \n", ss);
// load the heap header data
Dog* heapHeadder = new(ss) Dog( 1, 2, 4);

推荐答案

您对API的使用略有减少:

Your use of the API is slightly off:

HANDLE WINAPI HeapCreate(
    DWORD flOptions,
    SIZE_T dwInitialSize,
    SIZE_T dwMaximumSize );

请注意,此调用的第二个参数是堆的初始大小,而不是堆的最大大小.如果将最大大小指定为0,则在耗尽初始池后,Windows将尝试为堆提交新的内存页.

Note that the second parameter to this call is the heap's initial size, not its maximum size. When you specify 0 for the maximum size, Windows will try to commit new memory pages for the heap once you've exhausted the initial pool.

编辑

请注意,Windows将舍入的最大大小四舍五入到系统页面大小的最接近倍数.因此,堆的实际大小可能会超出您的要求.此外,堆会将部分内存用于自己的内部簿记.因此,您将无法进行等于堆大小的单个分配.

Note that Windows will round the maximum size given up to the nearest multiple of the system page size. So the actual size of the heap may be more than you requested. In addition, the heap will use some of this memory for its own internal book-keeping. So you won't be able to make single allocations equal to the size of the heap.

这篇关于HeapCreate和HeapAlloc混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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