- 浏览: 538058 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
landerson:
明显就有要求的嘛
ANDROID轻量级JSON序列化和反序列化[转] -
jimode2013:
很不错,就是需要这个方法
多个UIViewController使用addSubView,第二个 UIViewController 不响应旋转[转] -
w11h22j33:
...
[转]NSMutableArray中的自动释放对象让我郁闷了一整天 -
w11h22j33:
UILabel* label = [[UILabel a ...
Iphone开发 -
w11h22j33:
http://mobile.51cto.com/iphone- ...
获得通讯录中联系人的所有属性[转]
Finding iPhone Memory Leaks: A “Leaks” Tool Tutorial
There are plenty of different places to get a mobile application designed. The problem is that they’re quite expensive. You might be able to figure out how to create your own, but it will probably look very basic. Instead, a good mobile application development software can make it even easier, so that you can build great looking apps all by yourself.
The Mobile design Starter Kit includes all the themes and scenarios you need to build whatever app you want. There are customizable and standard files that allow you to sell or offer anything you want through the kit. Everything is there, so once you spend the money, you can create as many mobile apps as you want – and even sell the apps if this is your thing.
I’ve been using Instruments a lot lately as I approach the end of my game development cycle. I’ve found it especially useful for tracking down memory leaks in my game. I figured that since I found Instruments so helpful, it might be helpful for other people to get a quick introduction on how to use it to track mem leaks.
What is a memory leak and why should I care?
A memory leak is when your program loses track of a piece of memory that was allocated. The consequence is that the “leaked” memory will never be freed by the program. This usually happens when a piece of code does a “new,” “malloc,” or “alloc” but never does a corresponding “delete”, “free” or “release” respectively.
When you new, malloc, or alloc, what the Operating System is doing is giving your program a chunk of memory on the heap. The OS is saying, “here, have this block of memory at this memory address.” It expects you to hold a reference to that memory address (usually in the form of a pointer) and it’s relying on you to tell the OS when you’re done with it (by calling free, delete, or release).
Memory leaks happen when you throw away your pointer to that memory. If your program no longer knows where on the heap your memory is allocated, how can you ever free it?
So why should you care? In the most minor case, you’re wasting memory that will be freed when the user quits your app. In the worst case, you could have a memory leak that happens every frame. That’s a good way to end up crashing your program, especially if a user lets it run for a long time.
For more general information on memory leaks, have a look at Wikipedia for a start:
http://en.wikipedia.org/wiki/Memory_leak
How do I know I’ve got a memory leak?
Some memory leaks are easy to see by looking at your code. Some are much more difficult. This is where Instruments comes in. Instruments has a “Leaks” tool that will tell you exactly where you’re leaking memory so that you can get in there and fix it!
An Example App
I’ve created an example application that leaks memory in two places: in an Objective-C view controller, and in a C++ class I’m using in the app. The code is available from Github here. Below are excerpts from the code below that contain the leaks we’ll track down:
InstrumentsTestViewController.mm Excerpts
// Leaky excerpts - see GitHub for complete source - (void)viewDidLoad { [super viewDidLoad]; LeakyClass* myLeakyInstance = new LeakyClass(); delete myLeakyInstance; mMyLeakyString = [[NSString alloc] initWithUTF8String:"I'm a leaky string."]; [self doSomethingNow]; } - (void) doSomethingNow { mMyLeakyString = [[NSString alloc] initWithUTF8String: "Look, another alloc, but no release for first one!"]; }
LeakyClass.mm Excerpts
// Leaky excerpts - see GitHub for complete source LeakyClass::LeakyClass() { mLeakedObject = new LeakedObject(); } LeakyClass::~LeakyClass() { }
I’m going to go ahead a build my InstrumentsTest iPhone app in Debug and get it running on my iPhone. (You’ll have to set up the code signing to work on your device.) Once I’ve done that, I’ll boot up Instruments (typing “Instruments” into Spotlight should find it).
Instruments
When you launch Instruments, you should be given the chance to select from a variety of different Instrument tools to use. On the left-hand side, choose iPhone. On the right-hand menu, double-click the “Leaks” tool:
Once you’ve done that, you should see a window that looks like this:
Make sure your iPhone is still connected to your computer. In the top-left corner of the window you’ll see a drop-down menu that says “Launch Executable”. Click on that and make sure that your iPhone (not your computer) is selected as the active device. Then scroll down to “Launch Executable” and you should see a list of all the apps that are installed on your iPhone. Find the app that you want to run “Leaks” on (in this case, InstrumentsTest) and click it.
You’re now ready to go. Click on the red “Record” button and it will launch your application for you and start recording every memory allocation you do. It will also automatically check for leaks every 10 seconds.
You can change how often the automatic leak check runs, or you can set it to run only when you tell it too (when it checks for leaks, the entire app will freeze for about 3-5 seconds, so it can be annoying if you’re trying to play test and check for leaks at the same time). What I usually do is set it to manual control, and then hit the “Check for leaks” button whenever I need to (e.g. after loading a new game mode, after quitting the game back to the main menu, etc). Click on the Leaks row and use the View -> Detail button in the top right corned of the window to set/view options. For this example, I’m going to leave it on auto.
After the app has run for a few seconds, the auto leak check will run and lo and behold, it has found two memory leaks! Fantastic! What do we do now?
Extended Detail View
Instruments is very sneaky: it doesn’t make it obvious what to do next. What you need to notice is that row of buttons along the bottom of the window. See that little one made up of two rectangles? Hover your mouse over it and it will say “Extended Detail View”. (Note: You can also open this via View -> Extended Detail)
Click that button and a window opens up on the right-hand side of the screen that provides all kinds of handy details about your leaks!
Click on one of the memory leaks. The Extended Detail View will show you a complete stack trace to the point where your leaked memory was allocated. In our example above, clicking on the first leak reveals that a leak occurred inside [NSString initWithUTF8String]. If you look one step higher in the stack trace, you’ll see the last call inside my app was to [InstrumentsTestViewController viewDidLoad].
Here’s the really cool part, double-click on that line in the Extend Detail View and it opens an XCode window right to the culprit!
In this case we see that it was the first NSString allocation that leaked. Here’s where you need to do a bit of detective work. This is an extremely simple case, but it can get more tricky to find out why something’s leaky. Let’s take a closer look at our example.
In viewDidLoad we allocate some memory for the string, like this:
mMyLeakyString = [[NSString alloc] initWithUTF8String:"I'm a leaky string."];
And in dealloc, we release it like this:
[mMyLeakyString release];
So your immediate reaction might be that there shouldn’t be a leak. However, let’s search the code for all references to mMyLeakyString. That turns up this line inside doSomethingNow:
mMyLeakyString = [[NSString alloc] initWithUTF8String: "Look, another alloc, but no release for first one!"];
Notice that we’ve allocated a new string and assigned the pointer to mMyLeakyString. The problem is that we never released mMyLeakyString before it started pointing to something else. So the original string is now floating around on the heap and we have no way of freeing that memory. What the release call inside dealloc is actually doing is freeing the 2nd string that we allocated in doSomethingNow, because that’s where the pointer is pointing.
So, to fix this, we might change doSomethingNow to something like this:
- (void) doSomethingNow { [mMyLeakyString release]; mMyLeakyString = [[NSString alloc] initWithUTF8String: "Look, another alloc, but released first one!"]; }
What this does is release the first string we allocated before we point mMyLeakyString to our new string. When you build and run your app in Instruments again, you’ll see there’s one fewer memory leak. Of course, there are probably some better ways to handle NSStrings in your project, but if you had to do it this way, this would fix it.
Let’s take a look at that second leak. Clicking on it again reveals the callstack of what led to the leak. Finding the last call inside our app shows that the leak came from inside the LeakyClass::LeakyClass() constructor:
Double-click that in the stack and it opens up the culprit in XCode again:
Here we see the constructor does a new of a LeakedObject. But what’s this? The destructor never deletes the pointer? Well that’s no good! For every new, there needs to be a corresponding delete! So let’s change the destructor to this:
LeakyClass::~LeakyClass() { if (mLeakedObject != NULL) { delete mLeakedObject; mLeakedObject = NULL; } }
Build and run your app through Instruments again and you should be memory leak free!
I’ve chosen these two examples, even though they’re both very simple, because they show that Instruments can be used to track down memory leaks both in your Objective-C objects, as well as your C++ classes that are integrated into your app.
So go forth and fix your memory leaks! Because remember, a mem leak-free app is a happy app!
Similar articles:
发表评论
-
iOS App性能优化
2014-01-03 11:23 1695http://www.hrchen.com/2013/05/ ... -
iOS多线程编程Part 3/3 - GCD
2014-01-03 11:21 1649http://www.hrchen.com/2013/07/ ... -
iOS多线程编程Part 2/3 - NSOperation
2014-01-03 11:20 4546http://www.hrchen.com/2013/06/ ... -
iOS多线程编程Part 1/3 - NSThread & Run Loop
2014-01-03 11:17 7107http://www.hrchen.com/2013/06/ ... -
iOS移动网络环境调优那些事[转]
2014-01-02 17:10 2700http://xiangwangfeng.com/201 ... -
生成APNS Service证书的步骤[转]
2013-05-23 09:19 5678要进行推送服务的第一件事就是获取推送证书。它用来对你通过SS ... -
xcode 环境,多工程联编设置【转】
2013-02-28 21:59 8965http://blog.csdn.net/vienna_zj ... -
干掉你程序中的僵尸代码【转】
2012-12-22 11:05 966随着万圣节越来越流行,我感觉有必要跟大家讨论一下一个 ... -
一个文本框搞定信用卡相关信息的输入[转]
2012-12-22 11:03 1141http://beforweb.com/node/134 ... -
【转】深度技术分析“为什么ios比android流畅”
2012-09-23 19:41 1439原文 Andorid更新了一个版本又一个版本,硬 ... -
Iphone开发
2012-09-17 22:46 12071. NSClassFromString 这个方法 ... -
HowTo: Install iPhone SDK 2.0 – 3.1 for XCode 3.2[转]
2012-09-06 09:00 1224原文链接 So… you’ve installe ... -
Xcode 中设置部分文件ARC支持[转]
2012-08-03 10:57 1737ARC是什么 ARC是iOS 5推出的新功 ... -
xcode4 设置调试错误信息小结【转】
2012-07-19 14:37 1811方案1:NSZombieEnabled 先选中工程, ... -
[Cocoa]XCode的一些调试技巧【转】
2012-07-19 14:35 1207XCode 内置GDB,我们可以在命令行中使用 GDB ... -
[IPhone]如何使用Leak检查内存泄漏[转]
2012-07-19 14:34 1236简介 在IPhone程式开发中,记忆体泄漏(内存泄漏)是 ... -
获得通讯录中联系人的所有属性[转]
2012-06-21 14:04 1616获得通讯录中联系人的所有属性 ,看代码: ABAdd ... -
多个UIViewController使用addSubView,第二个 UIViewController 不响应旋转[转]
2012-06-20 23:51 16423------------------------------- ... -
shouldAutorotateToInterfaceOrientation 不触发或者不执行的问题[转]
2012-06-20 22:58 1463今天遇到一个很郁闷 ... -
UIViewController生命周期-学习笔记[转]
2012-06-20 22:57 1136UIViewController生命周 ...
相关推荐
这篇“Finding memory leaks发现内存的泄漏”可能是关于如何定位和解决内存泄漏的技术指南。 在C++编程中,程序员需要手动管理内存,通过`new`关键字申请内存,然后通过`delete`关键字释放内存。如果忘记释放或错误...
在压缩包中的文件,如`memory_leaks.shtml.htm`,可能包含了更详细的内存泄漏检测和解决方法。`VC Empire.htm`可能涉及到在Visual C++环境中如何处理内存泄漏的问题。阅读这些文件可以获取更多实用技巧和案例分析。 ...
《寻找阿尔法:量化构建交易策略》是一本深入探讨金融投资领域中量化交易策略的专著。阿尔法(Alpha)在投资领域中通常指的是超越市场平均收益的能力,是投资者追求的高回报目标。本书旨在通过严谨的定量方法,帮助...
- 类与对象:A*算法可能会封装在一个类中,包含节点、图、路径等对象。 - 文件操作:从Excel读取地形数据,这可能涉及到C#的文件I/O操作和对Excel文件格式的理解,例如使用`System.IO`和`Microsoft.Office.Interop...
char *strArr2[8] = {"a", "2", "c", "4", "e", "6", "g", "8"}; char **results = malloc(sizeof(char *) * 8); int i; mergeArrayIfDifferent(results, strArr1, strArr2, 8); for (i = 0; i ; i++) { ...
《CVPR 2018论文合集四》聚焦于一系列关键领域的研究,包括深度学习、计算机视觉(CVPR)、图像识别、自然语言处理(NLP)以及自动驾驶。这些领域在近年来取得了显著进展,推动了人工智能的发展。...
它的全名可能为"A Frog for Finding Vulnerabilities",正如其标题所言,它是一款专为发现系统漏洞而设计的高性能、高稳定性的扫描工具。在网络安全日益受到重视的今天,`afrog` 的出现为安全研究人员和开发者提供了...
IBM HeapAnalyzer is a graphical tool for discovering possible Java heap leaks. Steps Download: https://public.dhe.ibm.com/software/websphere/appserv/support/tools/HeapAnalyzer/ha457.jar Open a ...
finding a majority among n votes.pdffinding a majority among n votes.pdffinding a majority among n votes.pdffinding a majority among n votes.pdfv
标题"Astar.zip_A star planning_A* path finding_STAR_matlab A-star_mov"中提到的核心概念是A*(A-star)路径规划算法,这是一种在图形搜索中非常有效的寻路算法,广泛应用于游戏开发、机器人导航和地图路线规划等...
Finding Memory Leaks Issues with System RAM Issues with Battery Life Power Measurement Options Sources of Power Drain Addressing Application Size Issues Crash Reporting Using ACRA In-App Diagnostics ...
Although 2 GB of address space may seem like a large amount of memory, application such as SQL Server could leverage more memory if it were available. The boot.ini option /3GB was created for those ...
【标题】"Contact-Finding-App-" 是一个旨在帮助用户快速查找和过滤联系人的简单应用程序。这个应用的核心功能是根据用户输入的姓名关键字实时筛选出相应的联系人信息,从而提高查找效率。 【描述】提到的 "DOM操作...
本文介绍了一种系统化的方法——统一不可能差分查找方法(Unified Impossible Differential finding method, UID-method),用于高效地寻找各种块密码结构中的不可能差分。这种方法相较于先前由Kim等人提出的U-...
- **Technical Documentation Guide**: A guide to finding and using technical documentation, including online resources and community forums, is provided. #### Conclusion "Ubuntu Pocket Guide and ...
Finding Memory Leaks Issues with System RAM Issues with Battery Life Power Measurement Options Sources of Power Drain Addressing Application Size Issues The Role of Scripting Languages The Scripting ...
A Recommender System for Finding Passengers and Vacant Taxis
It serves as a blueprint for those in charge of finding solutions to this considerable challenge. Table of Contents Chapter 1: Software Modernization: a Business Vision Chapter 2: Software ...