gpt4 book ai didi

c - 调试和堆分配

转载 作者:行者123 更新时间:2023-11-30 17:03:51 25 4
gpt4 key购买 nike

在尝试处理 WinApi 中的堆时,我得到了 HeapAlloc 操作的一些奇怪结果。让我们考虑以下代码。问题是,根据 Microsoft Windows API 文档(下一个 - 文档),我必须将两个 Success 字符串打印到控制台。当我尝试在 MSVC 2013 中使用 Debud 选项运行此代码时,我收到 Error 。但最奇怪的是,当我尝试在没有 的情况下运行此代码时调试选项,或者运行编译后的.exe文件,我得到了正确的结果。

#include <Windows.h>
#include <stdio.h>

int main()
{
LPSYSTEM_INFO sys;
HANDLE hNewHeap;
LPVOID ptr;

sys = (LPSYSTEM_INFO) HeapAlloc(GetProcessHeap(),
0,
sizeof(SYSTEM_INFO));
GetSystemInfo(sys);
printf("Page size: %u\n", sys->dwPageSize);//Here we get the
//'Page size: 4096' string
//printed to the console


hNewHeap = HeapCreate(0, 1, 1);
//That's easy. We create new heap object, getting its HADNLE descriptor.
//According to Doc, the initial heap size is set to page size, which is
//4096 on my computer, like maximum heap size is also done. So the heap
//size now is 4096.

ptr = HeapAlloc(hNewHeap, 0, 2624); //Here we allocate the memory
//block in our new heap, that might have 2624 bytes size.

if ( ptr ) printf("Success!\n");//Here we check if the HeapAlloc functio
//worked correctly and print the appropriate string.
else printf("Error!\n");
//On this time we get 'Success' string printed to the console and free
//allocated memory block
if ( ptr ) HeapFree(hNewHeap, 0, ptr);

ptr = HeapAlloc(hNewHeap, 0, 2525);//Here we try to allocate the memory
//block, which size is 2526. And, like previous time, we expect to get
//'Success'.
if ( ptr ) printf("Success!\n");
else printf("Error!\n");
//But we get 'Error' here!!!
if ( ptr ) HeapFree(hNewHeap, 0, ptr);

HeapDestroy(hNewHeap);
system("pause");
};

如果您对任何小于 2624 的数字尝试相同的操作,您将不会收到“错误”。如果您尝试使用超过 2625 的数字执行此操作,您将收到“错误”。但只有当调试选项打开时,我们才会收到“错误”。

有人可以解释一下为什么会这样吗?

PS:抱歉英语不好。

P.S.:奇怪的是数字 2625 不对应于任何函数或应用程序大小,有时我会得到正确的结果,即重新启动工作室或对代码进行一些更改后。(但只是有时)

最佳答案

您正在创建一个固定大小的堆。 documentation说:

The HeapCreate function rounds dwMaximumSize up to a multiple of the system page size and then reserves a block of that size in the process's virtual address space for the heap.

因此您的堆的固定大小为 4096 字节。

随后,您从此堆中的分配会失败,因为该堆对于要分配的 block 来说不够大。再次来自 documentation :

The system uses memory from the private heap to store heap support structures, so not all of the specified heap size is available to the process. For example, if the HeapAlloc function requests 64 kilobytes (K) from a heap with a maximum size of 64K, the request may fail because of system overhead.

正是这些堆支持结构导致了您的困惑。您认为堆中有足够的空间用于第二次分配,但您没有考虑堆支持结构。

HeapAlloc 的文档告诉您调用GetExceptionCode失败时。期望返回STATUS_NO_MEMORY

关于c - 调试和堆分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com