在Xcode中打开一些调试选项后,我得到了这个输出:
GuardMalloc[Roadcast-4010]: free: magic is 0x0000090b, not 0xdeadbeef.
GuardMalloc[Roadcast-4010]: free: header magic value at 0x43f49bf0, for block 0x43f49c00-0x43f50000, has been trashed by a buffer underrun.
GuardMalloc[Roadcast-4010]: Try running with MALLOC_PROTECT_BEFORE to catch this error immediately as it happens.
如何开启MALLOC_PROTECT_BEFORE
?
更新:
Mac Developer Library > Guard_Malloc记录了MALLOC_PROTECT_BEFORE
所做的事情:
libgmalloc的行为可以通过几个附加更改 环境变量:
MALLOC_PROTECT_BEFORE
如果设置了此标志,则libgmalloc会更加努力地检测缓冲区 欠载运行。具体来说,libgmalloc放置已分配的开始 缓冲区在虚拟内存页面的开头,然后保护页面 之前。缓冲区欠载然后导致错误。没有的行为 这个变量集是将缓冲区的末尾放在 分配的最后一页,并保护页面。
答案 0 :(得分:3)
要在Xcode中启用MALLOC_PROTECT_BEFORE,请在Xcode菜单中转到
产品>方案>编辑方案......
然后在弹出的页面中,转到Arguments并在Environment Variables下,添加MALLOC_PROTECT_BEFORE
并为其赋值1
。您可以在屏幕截图1中看到这一点:
要实际使用它,现在点击诊断并勾选“启用Guard Malloc”,如Scrrenshot 2所示:
然后点击“确定”即可完成。
要测试检测缓冲区欠载现在是否有效,请使用以下代码:
int* allocated = malloc(1024);
printf("If this is the last line printed, then MALLOC_PROTECT_BEFORE is enabled and buffer underruns are detected.\n");
int value = allocated[-5]; // fails if MALLOC_PROTECT_BEFORE is set AND activated
printf("The value read from unallocated memory space is %i.\n", value);
printf("If this line is printed, then MALLOC_PROTECT_BEFORE is NOT enabled and buffer underruns can occur unnoticed.\n");
free(allocated);
allocated = NULL;