I have a C++ class that I’m using from my Objective-C++ controller in my iPhone app. The C++ class does some calculations on some data, returns a result, and then is done — but it leaks like crazy. I’m wondering if I can somehow make use of Memory Zones (aka malloc zones aka allocWithZone) to solve this. My idea is to allocate the ObjC++ object in a new zone, and then somehow have the C++ objects all be automatically created in this new zone. Then, when it returns, I kill the zone, and all of the memory will automatically be recovered, even if it has been leaked.
However: the documentation seems to indicate if I allocation an object in a new zone X, objects that it allocs will not automatically also be in zone X. If that makes sense, does anyone know how to override that behaviour so that all subsequent allocs and mallocs by that object will be in the new zone X?
EDIT:
-
I should note that the thread will be running mainly C++ code, a large code base, and it’s not economical at this point to kill all of the leaks in it since it was automatically converted from Java and leaks like crazy all over the place (refactoring required…). Thanks for the “just fix your leaks” advice but that’s not practical at the moment.
-
The memory is not being leaked through ObjC allocations, but mainly through C++ array new calls (a couple of direct mallocs as well). If that makes a difference.
Originally, zones in Objective-C were designed to enable the developer to allocate a bunch of related objects in a zone and then release them all without individually deallocating each instance.
In practice, this proved to impractical. Especially once the move from Object to NSObject was made (from NeXTSTEP to OpenStep).
The reality is that object graphs within applications are generally complex enough that total zone isolation of a sub graph is nigh impossible. In particular, you can’t allocate, directly or indirectly, any objects from Apple’s frameworks and hold references to them because you have no way of controlling the zone based allocations of said objects.
So, no, don’t do that. Fix your leaks. There is no magic bullet / mechanism to avoid having to make your code actually work.