HeapCreate and HeapAlloc Confuse

戏子无情 提交于 2019-12-13 18:25:31

问题


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

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

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

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.

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?

Thanks,

Here is test code.

// 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);

回答1:


Your use of the API is slightly off:

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

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.

EDIT

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.



来源:https://stackoverflow.com/questions/14406818/heapcreate-and-heapalloc-confuse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!