Question

Further to this question I've fixed a bunch of memory leaks in BEncoding.m (originally from here)

I've fixed all the obvious memory leaks, but Clang has found four "Leak of returned object" bugs, which I'm not sure how to sort:

The full messages/appropriate bits of code are:

NSMutableData *data = [[NSMutableData alloc] init];

[1] Method returns an Objective-C object with a +1 retain count (owning reference)

[...]
snprintf(buffer, 32, "%lu:", [object length]);
[data appendBytes:buffer length:strlen(buffer)];
[data appendData:object];
return data;

[3] Object returned to caller as an owning reference (single retain count transferred to caller)

Was it helpful?

Solution

OK, so to expand the answer above (thanks for setting me on the right track) ...

return [data autorelease]

You have allocated some object, "data", and are about to return this object back to the caller. The way this works in Obj-C is that at some level up the call stack, there is an NSAutoreleasePool. When you send the "autorelease" message to data, it adds itself to that autorelease pool. This allows the caller to use the "data" object briefly (ie, over the duration of the local stack frame) without needing to call "release" explicitly, and eventually, when the autorelease pool "pops", data will be deallocated (unless someone calls "retain"). That's rather clever.

Sweet. I think I just earned my green belt in Obj-C memory management.

OTHER TIPS

you want:

return [data autorelease];

since you're handing it to the caller.

It sounds like the objects aren't being properly autoreleased before they're returned, which violates the Objective-C memory management conventions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top