One of my all-time favorite industry books is “Writing Solid Code” by Steve Maguire. (As you may already know.) The principles spelled out in the book are timeless, even if the implementation examples are getting old.

I’ve been using iOS environment variables to implement some automatic tests for memory issues for a while:

  • NSZombiesEnabled
  • MallocStackLogging
  • MallocStackLoggingNoCompact

The first is a big help for getting the system to tell you when you are trying to use pointers to Objective-C objects that have already been freed. The other two help find where in code a pointer was freed. They’ve been such a help that I leave them on full-time.

Yesterday I started using some of the other environment variables available. These can be a big help for finding memory management issues in your C and C++ code (legacy or not.)

These are very good for executing the Solid Coding principle “Fortify Your Sub-Systems”. Or, as I prefer to think of it, “shred your garbage”. Basically, Apple fortified the allocation subsystem for you.

  • MallocScribble – causes system allocation functions to write 0×55 over all freed memory blocks.
  • MallocPreScribble – causes system allocation functions to write 0xAA over all new allocated memory blocks before returning them.

About an hour after turning these on, I had my first hit on a dangling pointer. A pointer that was an instance member of a C++ object was set to 0×55555555 after the object had been freed. Trying to dereference it threw the EXC_BAD_ACCESS exception and dropped me into the debugger. (See my post on how to make execution stop at the beginning of an exception.)

A “random” crash is now not random and found.