How To Debug Memory Leaks with XCode

本文通过实战演示如何使用Xcode及Instruments定位并解决iOS应用中的内存泄漏问题,包括利用NSZombieEnabled检测释放后的对象访问、使用Build and Analyze进行初步检查以及借助Leaks Instrument深入分析。

http://www.raywenderlich.com/2696/how-to-debug-memory-leaks-with-xcode-and-instruments-tutorial



This is the second article in a three-part series on working with memory in Objective-C on the iPhone. In the first part of the series, we covered how to manage memory in Objective-C by using instance variables and reference counting.

No matter how well you understand memory management in Objective-C, from time to time you’re bound to make mistakes. But often there’s way too much code to search line-by-line for problems (unless you want your hair to turn gray!)

Luckily, Apple has provided some great ways to help you find memory-related problems in your applications. Sometimes these tools scare new developers, but they’re actually pretty awesome and easy to use!

That’s what this tutorial is all about. You’ll get hands hands-on experience using XCode and Instruments to debug and detect memory related problems.

This tutorial assumes you are familiar with memory management in Objective-C. If you are still shaky on the subject, you may wish to read the memory management tutorial first.

Getting Started

Our goal in this tutorial is to check for and resolve any memory leaks in an example app that illustrates common memory-related mistakes. So to get started, download a leaky app that I’ve put together for this tutorial.

Open up the app and run it in XCode. You’ll see a list of sushi in a table view. Try selecting several rows, and then – BOOM! You get the dreaded EXC_BAD_ACCESS error, and the debugger is no help:

The dreaded EXC_BAD_ACCESS

This can be very frustrating to many beginning developers, as it’s not clear where the problem is. Here’s the advice I generally give to developers when you hit an EXC_BAD_ACCESS error:

  1. Set the NSZombieEnabled argument in your executable options, which sometimes helps narrow down the cause
  2. Run with Apple Instruments such as Leaks to look for memory issues
  3. Set a breakpoint in your code and step through until you narrow down where it’s crashing
  4. Tried and true “comment out code till it works” then backtrack from there :]

So let’s try this out for ourselves by trying option #1 – turning on NSZombieEnabled.

Zombie Invasion!

Unfortunately, the NSZombieEnabled option has nothing to do with the zombie apocalypse, so you can put away your boomsticks and chainsaws :]

Sorry, it's not those kind of zombies!

Sorry, it's not those kind of zombies! Image credit: werewolf from sxc.hu.

NSZombieEnabled is a flag that you can enable that will provide a warning when you try to access an object that has been deallocated. And since accessing deallocated memory is one of the most common reasons for crashing, this is a good thing to try first.

To set this up, expand the Executables group in your sidebar in XCode, and double click the PropMemFun executable. Select the Arguments tab, go to the “Variables to be set in the environment” section, and click the Plus button. Set the name of the variable to NSZombieEnabled, and set the value to YES, as follows:

How To Turn On NSZombieEnabled

Now run the app, and click on a few rows again until it crashes. Go to your console log, and you’ll see the following message:

2011-02-03 12:07:44.778 PropMemFun[27224:207] ***
-[CFString respondsToSelector:]: message sent to deallocated instance ...

The program will also halt on the exact line where it’s crashing now. You can go up the backtrace to find the exact line where it’s crashing by selecting the first area in the backtrace that is your code – in this case tableView:didSelectRowAtIndexPath.

Crash Location found with NSZombieEnabled

Aha! Now you know that in this line, a message is being sent to a deallocated string. This line uses two strings: _lastSushiSelected, and sushiString.

Well sushiString looks OK, because it’s initialized with stringWithFormat (which returns an autorelease variable), so it should be safe to use until the next run loop. But what about _lastSushiSelected?

_lastSushiSelected was set the last time this method was run to sushiString. But sushiString is an autorelease variable, so at some point it will be released, and the memory will be deallocated. But then _lastSushiSelected would still be pointing to deallocated memory! Which explains the problem – sending a message to deallocated memory causes a crash.

So to solve this, we just need to retain _lastSushiSelected so that the memory doesn’t go away. So replace the last line with the following:

_lastSushiSelected = [sushiString retain];

Compile and run your code, and now you should be able to run without crashing!

Build, Analyze, and Recognize

Ok, so we have an app that isn’t crashing – a good first step. But next, we need to start making sure that it isn’t leaking any memory.

There’s an easy way to perform an initial first-glance check on your app to see if it has any memory leaks or other problems – use the built-in Build and Analyze function.

This will make XCode run through your code and look for any mistakes it can automatically detect, and warn you about any potential problems. It doesn’t catch everything, but when it does catch things it’s a really quick and easy way to find out about the problems.

Give it a shot by selecting Build\Build and Analyze. You should see that it detected a memory leak, as you can see below:

Leak found with Build and Analyze

The message says that there’s a potential leak related to the “alertView”. If you look at this line, you’ll see that the UIAlertView was created with a alloc/init (which returns an object with a reference count of 1), but never released! There are several ways to fix this, but one way is to add the following after [alertView show]:

[alertView release];

Go to Build\Build and Analyze again, and you’ll see that there are no remaining issues.

Leaks and Plumbers

Unfortunately, you can’t rely on Build\Build and Analyze to catch everything. There’s one other great automated tool to help you check your app for leaks – the Leaks Instrument.

Let’s try it out. Go to Run\Run with Performance Tool\Leaks, and select a few rows in the table view. Also scroll up and down the table view from the top of the table to the bottom of the table. After bait of experimentation, you should start seeing some leaks popping up in the Leaks tab, which show up as blue bars.

Click the stop button, then go to the toolbar in the middle and click it to change from “Leaked Blocks” to “Call Tree”. In the panel in the lower left, click “Invert Call Tree”, and “Hide System Libraries”. You’ll see that it found two different methods in the code with memory leaks, as you can see below:

Leaks found with Leaks Instrument

If you double click a function name, it will take you directly to the line of code that creates the object that was leaked. This should give you a really good hint where the problem lies, and if you examine the code and think about it a bit, you should be able to figure out what the problem is and fix it.

So why not take a look at the code and see if you can figure out what the problem is and fix it? Once you’ve made a fix, you can run Leaks again and verify that the leak no longer occurs. Come back here once you’ve finished, or gotten stuck!


…waiting…

…waiitng…

…waiting…

Tomato-San is angry!

Tomato-San is angry!

What?! Are you still reading here?! You can do it – go ahead and try! :]

The Solution

tableView:didSelectRowAtIndexPath

Leaks tells us that the string created and stored into sushiString is leaked. So let’s think through why this is, step by step:

  1. When sushiString is created, it’s created with stringWithFormat. This returns an object with a retain count of 1, and a pending autorelease.
  2. In the last line in the method, you call retain on the sushiString (bumping the retain count up to 2) and store it into _lastSushiSelected.
  3. Later on, the autorelease takes effect, decrementing the retain count to 1.
  4. Next time the tableView:didSelectRowAtIndexPath method is called, you override the _lastSushiSelected variable with a pointer to a new string – without releasing the old one! So that old string still has a retain count of 1, and is never released.

One solution to this is to add the following line before setting lastSushiSelected to the sushiString:

[_lastSushiSelected release];

tableView:cellForRowAtIndexPath

Just like in the previous method, a string that’s created and stored into a variable named sushiString is leaked. Here’s what’s going on:

  1. A new string is created with alloc/init.
  2. This returns an object with a reference count of 1.
  3. However, this reference count is never decremented, so there’s a memory leak!

This could be solved in one of three ways:

  1. Call release on sushiString after setting the textLabel to the string.
  2. Call autorelease on sushiString after creating it with alloc/init.
  3. Instead of using alloc/init, use stringWithFormat, which returns a string already marked as autorelease.

Plumb the Leaks!

Fix the above two problems, compile and run Leaks again, and verify that you no longer have any leaks in the app!

Where To Go From Here?

Here is a sample project with the updated app, with no leaks or crashes.

At this point, you should have some good hands-on experience with how to find memory leaks in your app using NSZombieEnabled, Build and Analyze, and the Leaks Instrument. You should be able to apply these techniques to your projects to help find and resolve memory leaks!

Next check out the third article in this series, where I cover how to check your apps for memory leaks or memory-related mistakes, via using Instruments and other helpers.

If you have any other advice or tips to developers for good techniques to find memory leaks in your apps, please add your thoughts in the comments below!

### Xcode Debug Gauges 内存统计方式解释 Xcode 提供了强大的调试工具,其中 Debug Gauges 是用于实时监控应用程序运行时资源消耗情况的重要功能之一。Debug Gauges 位于 Xcode 的调试界面中,可以在调试过程中实时显示包括内存使用、CPU 占用、磁盘活动、网络请求等多项指标。对于内存统计,Debug Gauges 提供了直观的图形化界面,开发者可以快速识别内存使用趋势和潜在的性能瓶颈。 Debug Gauges 中的内存统计主要基于设备运行时的内存分配情况,通过 Xcode 与设备调试器的通信获取实时数据。内存指标包括 **物理内存使用量** 和 **虚拟内存使用量**,分别反映了应用在物理内存和虚拟内存中的占用情况。这些数据通过图表形式展示,开发者可以观察到内存使用的波动情况,并结合代码执行路径进行分析[^1]。 在调试过程中,Xcode 会定期采集内存使用快照,并将这些快照数据以时间序列为单位展示在 Gauges 界面中。通过这种方式,可以识别内存增长趋势,判断是否存在内存泄漏或内存抖动现象。例如,如果内存使用呈现持续上升趋势,可能表明存在未释放的对象或内存分配过高的问题。 此外,Debug Gauges 还支持与 **Instruments** 工具联动,开发者可以在 Gauges 界面中点击“Profile in Instruments”按钮,进入更详细的内存分析界面。Instruments 提供了更深入的内存跟踪功能,如 **Allocations** 和 **Leaks** 工具,可以进一步分析对象的生命周期和内存分配路径。 在 Debug Gauges 中,内存统计数据的采集频率和精度依赖于 Xcode 的调试器(LLDB)与设备之间的通信机制。Xcode 9 及更高版本中引入了更高效的调试协议,使得内存统计的实时性更强,数据更新更迅速。这也使得开发者可以在调试过程中更快地发现和修复内存相关问题。 以下是一个简单的调试示例,展示了如何在代码中触发内存分配行为,并通过 Debug Gauges 观察其影响: ```swift import UIKit class ViewController: UIViewController { var data = [Data]() override func viewDidLoad() { super.viewDidLoad() // 模拟大量内存分配 for _ in 0..<100 { let largeData = Data(repeating: 0, count: 1024 * 1024) // 1MB per allocation data.append(largeData) } } } ``` 在调试该代码时,可以通过 XcodeDebug Gauges 观察内存使用曲线的变化,从而判断内存分配行为是否符合预期。 ### 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值