TweetFollow Us on Twitter

Debugging Retain Count Bugs

Volume Number: 21 (2005)
Issue Number: 4
Column Tag: Programming

Tips From Big Nerd Ranch

by Aaron Hillegass, Chris Campbell, and Marquis Logan

Debugging Retain Count Bugs

At the Big Nerd Ranch, we teach the world's greatest Cocoa programming course (and the greatest Python, PHP, Perl, and PostgreSQL classes). One of the things that makes the course great is the alumni mailing list. We thought it would be a great service to the larger developer community if we shared some of the tips that have appeared on the list. So each month, we are going to cull through the discussion and publish a few pieces of useful wisdom. This month, we are talking about how to debug errors in the use of retain and release.

Hunting down bugs in your use of retain and release can be very difficult. Before delving into all the ways to find them, let's quickly review the lifetime of an object on the heap. The object is allocated (through the +allocWithZone: method which calls the malloc_zone_calloc() function), it is used, and then it is deallocated (through the -dealloc method which calls the malloc_zone_free() function).

Complicating matters is the retain count. A newly allocated object has a retain count of 1. When an object is retained, the retain count is incremented. When it is released, the retain count is decremented. When the retain count goes to zero, the object is deallocated.

This is complicated even further by the autorelease pool. When an object is sent the message autorelease, it adds itself to the current autorelease pool. When the autorelease pool is deallocated, it send the message release to every object in the pool. In a Cocoa application, the autorelease pool is deallocated after each event is handled.

Use release when possible

Here are two similar erroneous methods:

- (void)bad
{
    NSArray *array = [[NSArray alloc] init];
    [array release];
    [array release];
}

- (void)worse
{
    NSArray *array = [[NSArray alloc] init];
    [array release];
    [array autorelease];
}

The first method is run inside a debugger, it will stop on the erroneous line with a BAD_ACCESS error. The second method will cause a BAD_ACCESS only when the autorelease pool is deallocated. In a large program, it may be difficult to back track to where you autoreleased that object. Using release, besides being more efficient, will make your code easier to debug.

Note that this does not mean that you should break conventions: when creating an object to be vended out, it should be autoreleased:

- (NSNumber *)currentPrice
{
    NSNumber *p = [[NSNumber alloc] initWithInt:(whatTheMarketWillBear - 1)];
    [p autorelease];
    return p;
}

Set Pointers to nil after Objects are Released

To make it impossible to send messages to released objects, set the pointer to nil after the object is released:

- (void)fireThem
{
   [employees release];
   employees = nil;
}

Using Zombies

This code (which uses an object after it has been deallocated) often runs without crashing or throwing exceptions:

- (IBAction)stupidAction:(id)sender
{
    NSMutableString *string = [[nameField stringValue] mutableCopy];
    [string release];
    NSMutableString *anotherString = [NSMutableString stringWithFormat:@"I'm new!"];
    NSLog(@"string = %@", string);
}

The new string object is sometimes created in the same place in memory that the old one had occupied. So, when you run this you sometimes see:

string = I'm new!

On the other hand, sometimes the new string isn't created in the same location and the application crashes with a BAD_ACCESS. As you can imagine, hunting down a bug may or may not rear its ugly head can be maddening.

To debug this code, instead of freeing the memory for reuse, turn the objects into zombies. When you try to use a zombie, Cocoa will throw an exception. Thus, you can consistently reproduce this bug. The trick, then, is to tell Foundation and CoreFoundation, that you want to zombify your objects instead of freeing them.

First, you need to use the debug version of the CoreFoundation framework. To do this, select your executable in Xcode, and in the inspector under the General tab, choose "Use the debug suffix when loading frameworks."

Then, under the Arguments tab, set the environment variable NSZombieEnabled to YES and CFZombieLevel to 5:

Now when you send a message to a released object you will get a nice exception like this:

*** Selector 'respondsToSelector:' sent to dealloced instance 0x328840 of class NSMutableString.

(Remember to disable zombies once the bug is found -- you want the objects to be freed, not zombified in a deployed app.)

Putting a breakpoint on exceptions

Now that you have an exception that is thrown consistently, you will need to create a breakpoint in the debugger where the exception gets raised. Before dealing with the debugger, let's review how exceptions get thrown.

The Cocoa libraries check certain conditions, and if the conditions are not met, they raise exceptions. For example, if you ask for the second item in an array that has only one item, an exception will be thrown. Throwing an exception looks like this:

if (x == 13) {
    NSException *badness = [NSException exceptionWithName:@"BadLuckException"
                                                    reason:@"13 is unlucky"
                                                    userInfo:nil];
    [badness raise];
}

Thus, to stop the debugger as soon as an exception is raised, you can add the breakpoint for -[NSException raise] using the breakpoint panel.

Gradually, Cocoa programmers are moving to the new @throw/@catch/@finally form of exceptions stolen from C++ and Java. In this form, you will throw exceptions like this:

    NSException *badness = [NSException exceptionWithName:@"BadLuckException"
                                                   reason:@"13 is unlucky"
                                                   userInfo:nil];
    
    @throw badness;

(To use new-style exceptions, you must pass the -fobjc-exceptions flag to the compiler.)

To detect when an exception is being thrown from within the debugger, you will want to create a breakpoint on objc_exception_throw().

You will want these breakpoints every time you run the debugger. To automatically add these breakpoints anytime you use gdb, create a .gdbinit file in your home directory and include these lines:

fb -[NSException raise]
fb objc_exception_throw()

Those are the four tips for this week:

  • release instead of autorelease when possible
  • After releasing an object, set pointers to it to nil
  • Use zombies to hunt down retain/release problems
  • Add breakpoints to stop on exceptions

We hope they are useful to you, and we will be back next month with a few more.


Aaron Hillegass, Chris Campbell, and Marquis Logan

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »

Price Scanner via MacPrices.net

B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Beauty Consultant - *Apple* Blossom Mall -...
Beauty Consultant - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.