I’d like to use a custom malloc and free for some allocations in an iOS app, including those made by classes like NSMutableData.
- Is this possible?
- If so, how do I do it?
What I’d actually like to do is zero out certain data after I’ve used it, in order to guarantee forward security (in case the device is lost or stolen) as much as possible. If there’s an easier way to do this that doesn’t involve replacing malloc then that’s great.
I believe I need to replace malloc in order to do this because the sensitive data is stored in the keychain — and I have no option other than to use NSDictionary, NSString and NSData in order to access this data (I can’t even use the mutable versions).
Instead of overwriting generic memory management functions you can use custom allocators on the sensitive objects.
The keychain services API is written in C and uses Core Foundation objects, like CFDictionary, CFData and CFString. While it’s true that these objects are “toll free” bridged to their Objective-C counterparts and are usually interchangeable they have some abilities not available from Objective-C. One of these features is using custom allocators.
CFDictionaryCreatefor example takes an argument of typeCFAllocatorRefwhich, in turn, can be created usingCFAllocatorCreate. The allocator holds pointers to functions for allocation and deallocation, among others. You can use custom functions to overwrite the sensible data.