如何在Xcode中启用MALLOC_PROTECT_BEFORE?

5

在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将分配的缓冲区的开始放置在虚拟内存页面的开头,然后在前面保护该页面。缓冲区下溢会导致错误。如果没有设置此变量,则行为是将缓冲区的末尾放置在分配的最后一页的末尾,然后保护其后面的页面。

1个回答

5
为了在Xcode中启用MALLOC_PROTECT_BEFORE,您需要在Xcode菜单中转到Product > Scheme > Edit Scheme...,然后在弹出的页面中,转至Arguments并在Environment Variables下添加MALLOC_PROTECT_BEFORE,并将其值设置为1。您可以在屏幕截图1中看到这一点:Screenshot 1: adding MALLOC_PROTECT_BEFORE 为了确保实际使用该选项,请现在点击诊断,并标记“启用Guard Malloc”,如屏幕截图2所示:Screenshot 2: Enable Guard Malloc 然后点击OK即可完成。
为了测试是否现在可以检测到缓冲区下溢,请使用以下代码:
    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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接