No memory leaks, yet still running out of memory? - iphone

In my cocos2d application I have run through it using instruments and removed all memory leaks. I have my game outputting how much memory is in use on the screen and it is constantly rising as the game progresses until I eventually run out of memory. The amount of objects on screen doesn't increase by very much each level. Its a fairly simple game so i should not be running out of memory so soon.
I am removing all objects from a level when it ends and reallocating new ones when a new level begins. Instruments tells me there are no memory leaks. When i run through instruments to show me where the allocations are the bulk of the problem doesn't seem to come from one place its all of my objects.
Any ideas what the issue might be?

Just because instruments doesn't show leaks, doesn't mean you're not still allocating memory you're not using. Pay attention to the ObjectAlloc graph and see if that is constantly rising without falling off.

If you allocate memory that you aren't using and can't clean up, that's just as bad as a leak, even though you haven't technically leaked anything because you've stashed some unused reference somewhere.
Look at how much memory you actually need to use or to keep for future use at any point in your app, then treat anything else previously allocated as a leak and fix it.

In Objective-C when using autorelease objects be wary of circular dependencies!
If you create object A and then an instance of object B and pass A to it, so that B retains A, and A also retains B (for example by adding it as child to A) you can easily setup a circular dependency and thus both objects won't be released.
Tip: add a -(void) dealloc method to all your scene classes, and set a breakpoint there. If you change a scene and its dealloc method isn't called after the scene transition has finished, you're leaking this scene (it's not released).
Try to find that leak by looking for a setup that's similar to the one I described above.

Be careful about autoreleased objects, since they are not released immediately. If you have sections with lots of allocations and autoreleasing, try using specific autorelease pools on them.
It happened to me when creating huge decision trees (using NSArrays) for a game AI.

A great way to check for objects that are aggregating in memory is to use Instruments' new (in Xcode 3.2.3) Heap Shot functionality.
Use the normal Allocations instrument against your running application. Perform a series of repetitive events that should come back to some known state (for example, go one level down in a navigation controller and come back). Every time you do this, click on the Mark Heap button in the left sidebar for the Allocations instrument (under the section heading Heapshot Analysis).
What this will do is mark the heap at each of the starting points for this repetitive action and compare the objects that have been created by that point with the objects that had been created by the time you marked the heap last. Only objects that have been created between those two points and are still alive in memory will be listed.
If you are accumulating objects, but they are either not leaks or are being missed by the Leaks tool, they should show up here. I've found a number of subtle memory buildups this way, particularly when you pair this with the UI Automation instrument to automate the repetitive actions you're testing.

The bulk of the problem seem to be that Sprites don't get released in cocos2d unless all actions have been stopped on those sprites. This is done using stopAllActions. Cheers for all the suggestions.

Related

How to know what actually is those blue blocks in Instruments?

I am using Instruments to find memory leaks in my app.
When a object alloc, a blue block(line) display in Instrument, like this:
Screenshot of Instruments's timeline, showing the Allocations graph http://naituw.com/temp/instruments.png
When the object have been release, the blue line will disappear.
But when I make some operation in my application, some blue block left there, doesn't disappear, How can I know what those block actually is in the memory? Thanks!
Select the instrument and look in the list in the lower half of the window. It will show a table or outline (depending on the instrument) listing what the instrument recorded.
For the Allocations instrument, it lists things your application has allocated. Depending on the view settings, they may be objects that are still alive or all objects, even those that you have freed.
For the Leaks instrument, it lists things your application has allocated and leaked (i.e., no longer has any reference to). Note that you might still be wasting ever-increasing amounts of memory on things you will never use, not because you don't have a reference to it but because it's in a write-only cache (you stash it but never look it up) or similar situation. Bill Bumgarner calls this “abandoned memory”.
With either instrument, you can click on ➲ buttons within the list to drill deeper down into it, to see the list of allocations of a given type (e.g., all NSImages) or everything that happened to a single object, from birth to death. The latter is extremely useful for hunting down both leaks and over-release crashes, and is the reason why Instruments's Zombies template is so much better than NSZombieEnabled.
In leaks instrument these shows the memory allocations that took place at the particular time.

What does <non-object> in Allocation "heapshots" mean?

I'm having a hard time fixing memory related issues in my iPad application, but, good thing is, that I've learned about "heapshots" because of that. Bad thing is, I'm still unable to figure out what some of the information provided to me means.
So, what are these non-objects which are still alive and takes most of the memory described in Heap Growth? Is it possible to get rid of them? It looks like that most of them are related to various drawing operations, CALayer, context and etc (Category:"Malloc" or "Realloc"). I can provide more details if needed.
It means that memory block was allocated not for an object (e.g. pure c structure).
Usually they are allocated by system framework code, so there are some other objects that leaks. E.g. if you forgot to release UIView, then it's layer will not be freed too.
You can open "Extended detail" panel (see "View" menu) and analyze the call stack. Take in mind that one release you forgot can lead to a lot of memory leaks, so try to fix the easiest leaks and then check whether other leaks disappears.
One more trick. You can disable functional block of your application one by one and see whether leaks disappears. So you will be able to locate module (class, functional block, etc) where it occurs.

Memory crashes in iOS with real memory usage only at 5megs

I have been hunting down memory leaks for some time in my app. As of right now, as I flip back and forth between two views while watching the memory monitor instrument, the real memory fluctuates between 5 and 6 megs. This is all fine -- as far as I can tell everything is getting released properly when I pop back off a view. However, the virtual memory continues to increase and my available real memory drops rapidly every time I push the view back onto the view stack (even though the real memory usage of the app isn't increasing). Eventually, this all leads to an out of memory crash. Is this a telltale sign of any specific issue, or am I just missing a memory leak somewhere?
EDIT: The odd part is, I get an out of memory crash while the app is still only using up about 5 megs of real memory.
Do not use -retainCount.
The absolute retain count of an object is meaningless. It is an implementation detail. It may be influenced by many factors well beyond your code.
You should call release exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).
See the Memory Management Guidelines for full details.
In this specific case, you are leaking memory but in a way that leaks can't find it. The objects that are leaked are still connected to your overall application's object graph somehow. Maybe through a notification, maybe through delegation, doesn't matter -- leaks sees the reference and concludes that the object might still be live.
Use the Allocations Instrument. Configure it to only track live allocations (since you don't care about objects that have been deallocated). Do some stuff with your app. Check out what Allocations knows about and explain why all those objects should stick around. You can use the data mining facilities to filter down to just your objects.
Anyway, you can also use the "Build -> Build and analyze" option to find suspicious non-conventional code.
Another reason why you may have memory lost in lower API layers is if you don't remove all your views from your view hierarchy (aka : not calling [view removeFromSuperview] everywhere). At least that's what seemed to have happened to me.
Note that most of time this isn't required, as you would simply release the main view and all its subviews, then rebuild it from the view controller when needed. Things start to get more tricky when you're not releasing the whole hierarchy but instead simply remove some of them from the hierarchy.
In that case, I came to the conclusion that you may have buffers or layers still cached in lower API parts, and in that case your Allocation instrument won't help you.
In order to monitor correctly you'll need to use the "Memory Monitor" (in System). You'll see that the "Physical Memory Free" line dropping close to 0 is the most reliable indicator that a Memory Warning will be issued.
Another advantage of using this instrument, is that you can attach it to a running process, thus making it possible to have console output and instrument running together easily.
Circular references also won't be counted in Leaks but you can track those in Allocations. Best bet is to fire up Allocations and get to a state where you think everything should be gone (or certain objects should be). If they're hanging around go dive in to them and look at where they've been retained and sort out the proper memory ownership/releasing.
As for Allocations, there are some things that it doesn't track that can affect the overall memory. Some of the things include some CGImage backing stores, some CoreAnimation stuff and some database stuff.
Have you used the "Leaks" Performance Tool? And check out the logs in Organizer to see if there's anything there.
Also look into the dealloc for the view controllers and make sure you are properly releasing all of it's objects?

Understanding the Instrument for memory leak checking - iPhone

Above given images is of my application leaks.
Here I want to understand that, in Extended Detail - you can see different colors like light green, light pink, light brown, light purple.
What does each color indicates?
Now the other confusion is "How to locate the code which is creating a memory leak?"
Upto what limit of memory leak - the actual iPhone can go on with.
(suppose 10 bytes no problem, 20 bytes no problem & 200 bytes a problem)
What does each color indicates?
Which color indicates our code / From which detail we can get to the code where we have allocated the object & forgot to dealloc it?
(For example - On clicking of UIKit second cell in detail - we cant get to the code)
Why we must resolve all the leaks? - even a single leak can chock up iPhone ?
Why iPhone allows leaks to be remain in memory? / why garbage collection isn't done automatically after termination of application?
If I try to dealloc objects which should be deallocated according to instruments, My application terminates abnormally. If I don't dealloc, My application runs perfectly, How?
Why it is suggested that you wait in a view up to 10 or more seconds, if there is a leak, leak will be detected by Instruments?
Ignore the colors, in that one the [DashBoard viewDidLoad] is the source of the leak, something in how it's initializing a URLConnection (possibly you did not free that when the connection was finished?)
Now to answer the other questions you had:
Why we must resolve all the leaks? -
even a single leak can chock up
iPhone ?
Yes. Part of the reason is not only that you will simply run out of memory, but since there is only so much memory to go around for the whole phone a watchdog application is constantly monitoring your app and will shut it down early if it sees memory use only ever growing...
Why iPhone allows leaks to be remain
in memory? / why garbage collection
isn't done automatically after
termination of application?
All your application memory is freed when the app quits.
If I try to dealloc objects which
should be deallocated according to
instruments, My application
terminates abnormally. If I don't
dealloc, My application runs
perfectly, How?
Here I can't help, you really need to read more on the retain/release memory cycle... if you release an object that has a retain count of 0, the app crashes because the object is gone.
Why it is suggested that you wait in
a view up to 10 or more seconds, if
there is a leak, leak will be
detected by Instruments?
Because instruments works by sampling memory every so often, so it might take a little bit for instruments to get around to reading the memory after an action.
First of all, the things in the stack are colored by which library they come from, so it doesn't contain that much information.
Second, instead of worrying about how much leakage the iPhone can take, I'd focus on not having it leak.
To find leaks, there are a couple options:
Use the CLANG static analyzer when building your project
Look for leaks manually. You must always follow The Rules of memory management: if you alloc, retain, or copy an object (including using #property (retain) or (copy)), you must release or autorelease it.
The colors represent the different libraries the call stack is going through.
The leak is caused by the frame in your code that made the allocation, even if the actual allocation is taking place deep within an OS library. Instruments is showing you exactly where the leaked memory was allocated. You'll have to figure out which line in your code resulted in the leaked allocation, which will be one of the frames in the stack on the right.
The actual iPhone doesn't have much RAM available to your application. I tend to conservatively estimate about 25MB of RAM for my application to work with. Any leak, no matter how small, can sink the proverbial ship if the code is used enough.
Look for your application name in the stack extended view. Memory allocation usually shown in the end, so you know exactly which library is responsible for memory allocation. So you should trace from the line your code appear downwards till the end. Colors just make easier to trace lines of code, that are related to same libraries. Same library calls will be colored with the same color.
As for tracing leak itself. First go to your application call by double-click on the line in extended view and try to understand what exactly leaks. Sometimes you can replace the leaking call with non-leaking substitute. For example, I used a call imageNamed to retrieve images from the bundle, the application was constantly crashing because of memory shortage. I just googled imageNamed leaks and found very useful article on how to implement image cash in my application. Indeed, imageNamed API leaks. There are API that leaks in iphone SDK.
Also, try to check how you're working with alloc/retain/release and so on, whether you release or autorelease your allocated memory.
Good luck in your detective work.
I too have problems with leaks in instruments. I run my app today for the first time using leaks and found several leaks. Leaks that shouldn't be leaks because there is no way for them to leak, unless some magical code is executing and raising the retain count of my objects. I understand the memory management guidelines, know how to use autorelease pools, etc. But even an empty view based app contained leaks if i put a few controls on it. And just click around 2-3 times. Go ahead and try it. I don't really understant the information instruments is trying to provide. Are those "leaks" really leaks, or just things that are suspicious to the instruments app? Should an empty app with no user code, only a few controls put on an empty view leak memory?

iPhone Development - Lessons in memory management

I need lessons in memory management. I have an application that uses multiple views (around 10), some of these are attached to tab controller. Problem is that I'm using images (many images that I load from a web service). I'm facing the following issues.
The memory keeps increasing when I scroll in the table view (why?) - I checked the CustomTableViewCell application from Apple's site, and it's showing the same signs when I run it with Instruments.
I'm using autorelease with many objects, but I see that these objects don't actually get released and the memory is wired. How can I get rid of these objects?
How can I tell the NSAutoreleasePool to periodically release the objects that are not being used? I think this can help me get rid of wired memory. But can I do that?
Is there any example by Apple or someone else (book or online articles) explaining how to use Instruments (in a little detail with example?) and to fine tune the application for memory and performance?
Thanks.
Now that we have the "just say no" answers to autorelease out of the way, I thought I'd add a tip on how to use autorelease more effectively. For better or worse not everyone's going to completely avoid autorelease-- if for no other reason than because Apple provides so many convenience methods that hand you autoreleased objects.
You can't just tell the autorelease pool to free up any objects that you're not using. There's no garbage collection, and how else is it going to know?
What you CAN do is to create a local autorelease pool and then release that when you no longer need the local autoreleased objects. If you have a block where you're creating autoreleased objects, you'll ensure they get freed by creating a local autorelease pool at the start of the block (just alloc/init it, no magic required) and then releasing the pool at the end of the block. And voila, and objects in the pool are also released.
Autorelease pools nest, so keep that in mind if you do this. If you release an autorelease pool, make sure it's the most-recently-allocated pool and not some other one.
The autoreleased memory is released when control is returned back to the system, but only when it chooses to. If you wish to force memory to be released use "release" which works there and then.
It should be noted that because of memory fragmentation that allocating and deallocating a block of memory may not seem to get you back to where you started in terms of measurable "free" memory.
Tony
For performance reasons, Apple recommends that you retain/release objects yourself whenever possible. autoreleasing them can cause excess memory usage as the autoreleased objects aren't always released immediately.
In other words, if you know you're done with an object, explicitly release it.
The UITableView has a way to reuse table cells that aren't being displayed anymore. That way if you only display 6 cells on the screen at once it doesn't keep on creating more as you scroll, but reuses the cells that have gone off screen. whenever you want to create a new cell, first query the tableview to see if it has any to reuse and if not then create a new one.
an example of this can be found on slide 55 of the standford iphone course note found here: http://www.scribd.com/doc/7671058/Standford-CS-193P-11Performance
According to Apple, you should not use autorelease and instead should retain and release objects explicitly as needed. autorelease will not release an object as soon as its function is over. If in the tableview you are using images downloaded from a webservice, try and cache these images and reuse them if possible. Another option is to only get those images which are being displayed.