如何在 Xcode 中启用 MALLOC_PROTECT_BEFORE?

Dan*_* S. 5 xcode simulator ios

在 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.
Run Code Online (Sandbox Code Playgroud)

如何开启MALLOC_PROTECT_BEFORE?

更新:

Mac Developer Library > Guard_Malloc 中MALLOC_PROTECT_BEFORE记录了什么:

libgmalloc 的行为可以通过几个额外的环境变量来改变:

MALLOC_PROTECT_BEFORE

如果设置了此标志,则 libgmalloc 会更努力地检测缓冲区欠载。具体来说,libgmalloc 将分配的缓冲区的开始放置在虚拟内存页面的开头,然后保护之前的页面。缓冲区欠载会导致错误。没有设置这个变量的行为是将缓冲区的末尾放在分配的最后一页的末尾,并保护之后的页。

Dan*_* S. 5

要在 Xcode 中启用 MALLOC_PROTECT_BEFORE,请在 Xcode 菜单中转到

产品 > 方案 > 编辑方案...

然后在弹出的页面中,转到 Arguments 并在 Environment Variables 下,添加MALLOC_PROTECT_BEFORE并为其赋值1。您可以在屏幕截图 1 中看到这一点:

截图 1:添加 MALLOC_PROTECT_BEFORE

要实际使用它,现在单击诊断并勾选“启用 Guard Malloc”,如 Scrrenshot 2 所示:

屏幕截图 2:启用 Guard Malloc

然后点击确定就大功告成了。

要测试检测缓冲区欠载现在是否有效,请使用以下代码:

    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;
Run Code Online (Sandbox Code Playgroud)