Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable MALLOC_PROTECT_BEFORE in Xcode?

After switching on some debug options in Xcode, I get this output:

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.

How do I switch on MALLOC_PROTECT_BEFORE?

UPDATE:

What MALLOC_PROTECT_BEFORE does, is documented at Mac Developer Library > Guard_Malloc:

libgmalloc's behavior can be changed with several additional environment variables:

MALLOC_PROTECT_BEFORE

If this flag is set, then libgmalloc tries harder to detect buffer underruns. Specifically, libgmalloc places the start of the allocated buffer at the beginning of a virtual memory page, then protects the page before. Buffer underruns then cause an error. The behavior without this variable set is to place the end of the buffer at the end of the last page of the allocation, and protect the page after.

like image 450
Daniel S. Avatar asked Jun 05 '14 11:06

Daniel S.


1 Answers

To enable MALLOC_PROTECT_BEFORE in Xcode, in the Xcode Menu go to

Product > Scheme > Edit Scheme...

and then in the page which pops up, go to Arguments and under Environment Variables, add MALLOC_PROTECT_BEFORE and give it the value 1. You can see this in Screenshot 1:

Screenshot 1: adding MALLOC_PROTECT_BEFORE

To make this actually being used, now click on Diagnostics and tickmark "Enable Guard Malloc", as shown in Scrrenshot 2:

Screenshot 2: Enable Guard Malloc

Then click OK and it's done.

To test whether detecting buffer underruns now works, use the following code:

    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;
like image 189
Daniel S. Avatar answered Oct 25 '22 12:10

Daniel S.