NAME
lliibbggmmaalllloocc..ddyylliibb - (Guard Malloc), an aggressive debugging malloc
libraryDESCRIPTION
lliibbggmmaalllloocc is a debugging malloc library that can track down insidious bugs in your code or library. If your application crashes when usinglibgmalloc, then you've found a bug.
libgmalloc uses the virtual memory system to identify such bugs. Each
malloc allocation is placed on its own virtual memory page, with the end of the buffer at the end of the page's memory, and the next page is kept unallocated. As a result, accesses beyond the end of the buffer cause abus error immediately. When memory is freed, libgmalloc deallocates its
virtual memory, causing reads or writes to the freed buffer cause a buserror. Thus, nasty, hard-to-track-down bugs are immediately obvious, and
you'll know exactly which code is causing the problem. This is thread-
safe and works for all uses of malloc(), NSZoneMalloc(), and friends.As of Mac OS X 10.5, libgmalloc now aligns the start of allocated buffers
on 16-byte boundaries by default, to allow proper use of vector instruc-
tions (e.g., SSE or Altivec). (The use of vector instructions is becom-
ing more common, including in some Mac OS X system libraries. The regu-
lar system malloc also uses 16-byte alignment.) Because of this 16-byte
alignment, up to 15 bytes at the end of an allocated block may be excessat the end of the page, and libgmalloc will not detect buffer overruns
into that area by default. This default alignment can be changed with environment variables.libgmalloc is available in /usr/lib/libgmalloc.dylib. To use it, set
this environment variable:set DYLDINSERTLIBRARIES to /usr/lib/libgmalloc.dylib
Note: it is no longer necessary to set DYLDFORCEFLATNAMESPACE.
This tells dyld to use Guard Malloc instead of the standard version of malloc. Run the program, and wait for the crash indicating the bad access. When the program crashes, examine it in the debugger to identify the cause. UUSSIINNGG lliibbggmmaalllloocc WWIITTHH TTHHEE XXCCOODDEE DDEEBBUUGGGGEERR OORR GGDDBBBecause the goal of libgmalloc is to "encourage" your application to
crash if memory access errors occur, it is best to run your application under a debugger such as the Xcode IDE's debugger, or gdb at the command line. To use Guard Malloc with the Xcode debugger, choose the "Enable Guard Malloc" menu item from the Debug menu before launching your executablefor debugging. That automatically sets the environment variables prop-
erly. Xcode retains that setting with that executable. If you need to set any of the additional environment variables described below, selectyour executable in the Groups & Files outline, then bring up the Exe-
cutable Inspector. Choose the Arguments tab, and add the environment variable to the environment variables list. If you're using gdb from the command line, use gdb's 'set env' command to set the environment variables. EEXXAAMMPPLLEE% cat gmalloctest.c
// cc -g -o gmalloctest gmalloctest.c
main() { unsigned *buffer = (unsigned *)malloc(sizeof(unsigned) * 100); unsigned i; for (i = 0; i < 200; i++) { buffer[i] = i; } for (i = 0; i < 200; i++) {printf ("%d ", buffer[i]);
} }% cc -g -o gmalloctest gmalloctest.c
% gdb gmalloctest
Reading symbols for shared libraries .. done(gdb) set env DYLDINSERTLIBRARIES /usr/lib/libgmalloc.dylib
(gdb) r Starting program: gmalloctest Reading symbols for shared libraries .. done Allocations will be placed on word (4 byte) boundaries.- Small buffer overruns may not be noticed.
- Applications using vector instructions (e.g., SSE or Altivec) may fail.
GuardMalloc-14
Program received signal EXCBADACCESS, Could not access memory. 0x00001d4c in main () at gmalloctest.c:9 9 buffer[i] = i; (gdb) print i$1 = 100
(gdb) where#0 0x00001d4c in main () at gmalloctest.c:9
(gdb) Once you have the backtrace, you can examine that line of source code to see what variable would have been accessed, and determine why that value would have been invalid memory. If you looked at the source for the example above, you might find that this function looks one character too far beyond the string it's operating on and causes a bus error when accessing the protected page following the string. These sorts of problems may seem minor, especially when the application normally behaves correctly. However, they're usually the hallmark of intermittent bugs or unexplained crashes in long running programs. In normal use, the bug in the example program might have caused no problemsat all... or it might have trashed the following buffer, leading occa-
sionally to corrupted data. If the application had been referencing freed memory, the program might have worked fine until the one time where the freed memory was immediately reused and modified. ENVIRONMENTlibgmalloc's behavior can be changed with several additional environment
variables:MALLOCPROTECTBEFORE If this flag is set, then libgmalloc tries
harder to detect buffer underruns.Specifically, libgmalloc places the mal-
loc-allocated buffer at the beginning of a
virtual memory page, then protects the page before. Buffer underruns then causean error. The behavior without this vari-
able set would be to place the buffer at the end of the page, and protect the page after.MALLOCFILLSPACE This flag causes libgmalloc to fill the
buffer with 0x55 upon creation. This can help catch uninitialized memory problems. MALLOCALLOWREADS This flag allows the guard page after the buffer to be readable so that reads pastthe ends of buffers do not cause the pro-
gram to crash. With the MALLOCPRO-
TECTBEFORE flag set, this command instead sets the guard page before the buffer to be readable. MALLOCVECTORSIZE This option is the default alignment, as of Mac OS X 10.5. With this option, Guard Malloc places allocations on 16 byte boundaries, because vector instructions (e.g., SSE or Altivec) require buffers to be on 16 byte boundaries. (The use ofvector instructions is becoming more com-
mon in some Mac OS X system libraries.) MALLOCVECTORSIZE is now the preferred name of this environment variable; the older MALLOCALTIVECSIZE is deprecated but supported for backward compatibility. MALLOCWORDSIZE This flag specifies that Guard Mallocshould place allocations on word (4-byte)
boundaries, with the end of the buffer on the last 4 bytes of the page. This option is useful because Carbon assumes that pointers are word aligned, and without the word alignment, any program relying on Cocoa or Carbon would immediately crash. MALLOCSTRICTSIZE This flag specifies that Guard Malloc should always align all allocations onsingle-byte boundaries such that the last
byte of the buffer is at the end of the page. This will immediately catch evenone-byte buffer overruns, but applications
that use Carbon or Cocoa, or vector instructions, may not run properly with this option. MALLOCPERMITINSANEREQUESTS GuardMalloc tries to protect against requests for insane amounts of memory byinstructing the program to trap (if run-
ning under the debugger) if more than 100MB is requested. If this environmentvariable is set, then the check is dis-
abled. MMEEMMOORRYY VVAALLUUEESS UUSSEEDD BBYY GGUUAARRDD MMAALLLLOOCCIt's often useful to understand how Guard Malloc uses memory when debug-
ging. Guard Malloc writes strange byte sequences to catch certain prob-
lems. The first buffer is placed at 0xb0000000, and subsequent alloca-
tions are placed in virtual memory from that point up. If the MAL-
LOCFILLSPACE environment variable is set, newly allocated buffers willbe filled with the value 0x55 in hopes of catching references to unini-
tialized memory. The space right before the buffer is dedicated to header information. The header is organized as:size of buffer + size of header (0x60 + requested size rounded to appro-
priate boundary) thread id stack backtrace where allocation occurred (twenty frames; longer stack traces are truncated, and smaller stack traces will leave the unused frames zeroed.) magic number (0xdeadbeef) beginning of buffer CCAAVVEEAATTSSlibgmalloc doesn't come without some weaknesses. First, because each
allocation requires two pages of virtual memory, only about 500,000 mal-
loc allocations could conceivably exist before you run out of virtual memory. The extravagant use of virtual memory will also cause much moreswapping, so the program will run much slower than usual - usually two
orders of magnitude (100x).Don't forget - if there's a memory bug in your program, the program will
crash in Guard Malloc. This is a feature!SEE ALSO
MallocDebug contains another debugging library, libMallocDebug, that doesn't affect running behavior as significantly. Mac OS X March 16, 2004 Mac OS X