Advertisement

Xcode 3.2 Daily Tip: Analyzing Your Code

More Xcode 3.2 tips for Mac and iPhone developers.

The LLVM/Clang static analyzer bundled with the Snow Leopard developer tools automatically detects a variety of memory management bugs in Objective-C programs. It's a terrific tool for finding memory leaks and other issues and it is now easily available to all developers, both for the Macintosh and iPhone platforms.

I first learned about using the analyzer with iPhone projects from a blog post by Joe Heck of rhonabwy.com. Heck pointed out that the Intel-only analyzer worked with the Intel-based Simulator code generated by the iPhone SDK, letting you use the analyzer with your iPhone projects.

At that time, you had to download a copy of the analyzer, install it by hand, and run it from the command line. It was amazingly helpful but a bit of a pain to use.

No more. Xcode 3.2 incorporates the static analyzer tool directly into its IDE. Choose Build > Build and Analyze (Command-Shift-A) and the analyzer automatically checks your code. and presents any bugs detected by the analyzer. Static analysis evaluates source code to automatically find bugs, issuing hints that are similar in nature to compiler warnings but targeted at Foundation (Cocoa) and Core Foundation memory management.

Each bug is marked with a blue icon and a description. I do wish that the text didn't seem to "cut off" so abruptly. Resizing the Xcode editor window does not affect the hard right alignment of the bug reports. This bug refers to the local watcher variable, which is allocated and initialized but not released.

The tool is not perfect. It may flag nonexistent "bugs" in programs, so there are definitely false positive results that will show up as well as gray areas. In this example, the watcher is used until the application teardown, so the fact that it's leaking is not really a problem. That having been said, the analysis is amazingly helpful and if you do find real bugs, the Clang Static Analyzer team solicits bug reports.

To learn more about your bug, click the blue branch icon in the code itself. The analyzer offers a detailed view of the bug and its issues. This presentation provides more information about the specifics of the issue at hand.

In this detail view, clicking any single blue arrow opens the Build Results pane, showing the analyzer result list. Hide or show analyzer information by clicking the blue branch icon in the left gutter.

It's easy to overlook the new built-in static analysis feature of Xcode 3.2, but you'd be missing out on a great feature if you didn't explore it further.