Memory leak with [NSMutableData appendData:]

Instruments reveals that the following simple code leaks memory on each delegate invoke:

- (void)start {
    [_urlSession dataTaskWithURL:_url];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [_data appendData:data];
}

I don't have any clue on this leak, it should not happen. What should I do to avoid this?

Replies

I'm not sure I follow your reasoning here.

In the first screenshot, the highlighted item is a 4MB memory block that was last resized in the delegate method, suggesting it's the memory block associated with your _data object reference. There's nothing to suggest that it's leaked there at all.

In the second screenshot, it looks like a leak of only 16 bytes was detected. That suggests it's the local data variable reference's memory, not _data and there's no evidence there that it's leaking every time.

I think in this scenario, the Leaks instrument isn't doing you any favors, because you have no insight into why it thinks this memory is being leaked. It'd probably be more productive to focus on the Allocations instrument (within the Allocations template), then use the "Mark Generation" button to isolate the allocations that remain after a specific download session:

https://developer.apple.com/documentation/xcode/gathering-information-about-memory-use/#Profile-your-app-using-the-Allocations-instrument

That should give you a clearer idea of which memory (if any) is actually being leaked.