How can I hook malloc on iOS?


I’d like to hook malloc for an iOS app in order to use a custom allocator (jemalloc) that I have benchmarked and seen that it improves my app’s performance. I know there must be a way to hook malloc, since the address sanitizer does it. Here are some possible routes:

  • Do whatever the address sanitizer does to wrap malloc. However, it’s hard for me to figure out what’s going on from the source code
  • Swap out the function pointers of the default malloc zone for my own, except that this is not safe
  • Use the zone manipulation in, except that this appears to have only been written with OS X in mind
  • Use CFAllocatorSetDefault, except that this seems to negate the speed wins that I see and will not cover cases where a library is using malloc rather than CFAllocatorAllocate
  • Use interposing to swap the functions early on, except that it doesn’t seem to come soon enough to catch all mallocs, and the custom allocator crashes when it’s told to free something allocated with the original malloc

Does anyone have any ideas?