[cfe-dev] Memory leak analysis and self destructing objects

Nikita Zhuk nikita at zhuk.fi
Fri Jun 20 01:42:05 PDT 2008


While running memory leak analysis I've noticed that it all objects  
which are self-destructing cause static analysis tool to produce false  
positives. By self-destructing I mean situations where ownership of an  
object is moved to the object itself, which then releases itself after  
certain operation has been completed (e.g. consider NSWindow, which  
can be set to release itself automatically after it's closed). Static  
analysis tool doesn't have this knowledge, and when it sees only an  
allocation without release, it reports memory leak.

For example:
-(void)awakeFromNib
{
NSWindow *window = [[NSWindow alloc]  
initWithContentRect:NSMakeRect(0,0,100,100)  
styleMask:NSTitledWindowMask|NSClosableWindowMask backing:  
NSBackingStoreBuffered defer:NO]; // isReleasedWhenClosed is set to  
YES by default
	[window orderFrontRegardless];

	// False memory leak reported - window will be released when user  
closes it
}

Fortunately self-destructing objects are not very widely used, and  
vast majority of objects use the traditional ownership semantics.  
However, these false positives could be suppressed if a special  
attribute could be used to mark objects with self-destructing  
semantics. This attribute would also serve as a documentation for  
these non-traditional ownership semantics, which would otherwise  
require a trip to documentation viewer. Maybe something like NSWindow*  
__attribute__((self_ownership)) window = ...? Unlike NSWindow, where  
self-destruction can be enabled or disabled at runtime, some classes  
use self-destruction all the time, so maybe some class-level  
annotation could be used.

In addition to this case there're some other cases where this  
attribute won't help. For example, a delegate object may be set to  
NSWindow, and NSWindow will notify the delegate object when window is  
closing. Delegate may then release the window by sending autorelease  
to it. This case will probably cause false positive memory leak report  
as well.

Any thoughts? Is there some generic way to suppress these false  
positives?

- Nikita






More information about the cfe-dev mailing list