Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Phantom Memory leak with ARC in XCode 4.5 where dealloc is definitely called or an Instruments issue?

Preamble; This is NOT a general "I have a giant app with a leak" question. It's a specific issue about either Automatic Reference Counting not working properly in a nearly trivial demo app, with full source code, or a subtle code generation or compiler issue, or a bug in Instruments. (TLDR: Oh. Actually an odd little race condition)

I'm confused by the fact that Instruments' "Allocations" list is showing an instance leak and yet, I have an instance of that class, only one, and ARC is causing the dealloc method to be called and I know it's being called because there is an NSLog message that gets printed when the dealloc is done, and yet it still shows up in the list of leaks in Instruments.

The retainCount never exceeds 1. It is not being retained by anybody, and it's being dealloc'd,and yet it appears like it's a "leak" because it show as an active instance in Instrument's leaks.

How is that possible?

I am still learning Objective-C with ARC, and so I think I must be making a common beginner mistake. Here is my only init and my object's dealloc:

- (id) initWithMessage:(NSString*)messageForUser
{
    self = [super init];
    if (self)
    {
        _message = messageForUser;
        NSLog( @"from constructor: %@",_message);
    }
    return self;

}

- (void)dealloc {
    NSLog(@"Goodbye cruel world. One WPMyObject signing off.");
   // [message release]; // ARC forbiddeth thee! Begone release.
    _message = nil;

   // [super dealloc]; // ARC forbiddeth explicit super dealloc
}

Just to see if I could, I tried to call [super dealloc] in the dealloc method, and ARC blocks you with an error, which is great because it's going to do that for you. However when I write my own init method, it does not block me.

When I run the program using "Run" in XCode, I get the "goodbye cruel world" NSLog message, as I hoped I would, when dealloc is run, yet I also get this evidence that the instance still exists at the end of the run, when Instruments analysis using memory leaks template is used:

If I run without the instance creation code below, I get only a few standard library malloc leaks reported, but if I add this code, all the leaks occur:

  WPMyObject * myObject = [[WPMyObject alloc] initWithMessage: @"Hello World!\n" ];

Here is what I'm seeing, and think I understand is telling me that WPMyObject's only instance is leaking:

enter image description here

The full source code which is quite trivial (a tiny Mac OS X command line app using Objective-C and Foundation/Foundation.h) is on BitBucket. Click this link to view the source code in your browser.

The main.m unit runs a single test object instance creation, inside an @autoreleasepool {...} context statement:

enter image description here

If you want to see the totally trivial code on your own computer, grab it like this:

  hg clone https://bitbucket.org/wpostma/objectivecplaymac

Update: You can fix the "leak" (which may be a bug in Instruments, or a clang/llvm compiler bug, and not a "real leak") by adding this line of code just before the } which ends the autorelease pool:

  NSLog( @"Reached end of autorelease pool" );

Yep. Add log message. "Leak" goes away. This is XCode 4.5.2 (4G2008a) on Mac OS X 10.7.5, containing Instruments Version 4.5 (build 4523).

Update2: It really is a simple multi-process race condition. The code below appears to be a reasonable Debug-build bit of hackery. If there was a more explicit way of saying "wait until Instruments is done with me, and then exit main()", that might be a nice future feature, Apple engineers. A PROFILER_SYNC("MESSAGE") macro that expands to nothing in release mode, but in debug builds, sends "MESSAGE" to the profiler.... It could be very handy indeed.

int main(int argc, const char * argv[])
{
    // This creates and cleans up an auto-release pool context.
    @autoreleasepool {

        foo(); // Microscopic amounts of debug code you want profiler to analyze go here.

#ifdef DEBUG
        usleep(10000); // race condition prevention in debug builds, so Instruments can finish up.
#endif

    }
#ifdef DEBUG
    usleep(10000); // race condition prevention in debug builds, so Instruments can finish up.
#endif

   return 0;
}
like image 242
Warren P Avatar asked Jan 10 '13 15:01

Warren P


1 Answers

Sounds less like a leak and more like a race condition. A race between the writing of the NSLog and the program's execution being terminated. Or a buffering issue, more likely, where the output isn't flushed until a certain threshold is reached.

Try putting a sleep(100); after the closing brace on the autorelease pool. Or try adding a bunch more text to the log message in the dealloc.

If that doesn't "fix" it, then show the disassembly and see what changes between the two versions of the code.


The reason why this happens: Both Instruments and NSLog() are effectively buffered for performance reasons. They are designed for use in a relatively long running process that almost always has either a main event loop or a call through to dispatch_main().

This is done to try and minimally impact the performance of the target application, but it can lead to weirdness in micro benchmarks where the process is extremely short lived.

If you have a minimal test case in a short lived process, I would recommend closing the main() with [[NSRunLoop currentLoop] run];. That'll run forever and give you a viable runtime for Instruments' and/or the debugger's sake.

like image 156
bbum Avatar answered Oct 10 '22 11:10

bbum