Garbage Collection and the Optimizer
There’s an interesting edge case in the Objective-C garbage collector that’s being discussed on Cocoa-dev. The collector treats variables on the stack as rooted, but the contents of the stack may not match what the programmer is expecting. If gcc’s optimizer determines that a particular variable will no longer be accessed, it can replace it on the stack before it goes out of scope in the Objective-C source. Ordinarily this is safe, but it can cause problems when dropping down to the C level. If the variable points to an NSData
, the object can be collected while a pointer to its contents is still in use. Mike Ash describes it nicely:
The problem here is that you’re expecting one pointer to keep a different pointer live, which the GC does not make any guarantees about.
Basically, under GC, my impression is that it should be considered invalid to return a pointer to a caller which depends on the lifetime of the parent object.
Unfortunately, there isn’t a simple fix because NSData
’s contents are not always a simple block of collectable memory.