Memory behavior of / Possible memory leak in UITableView - iphone

I am profiling my iPhone application with the 'Activity Monitor' Instrument. When I use UITableViews and scroll through them, I see the memory usage of my application go up all the time while I scroll. When I return to the previous view and the UITableViewController gets deallocated, the memory usage goes down a bit, but not to where it was previously. But the 'Leaks' instrument does not find any memory leaks, and neither does the static analyzer find some. I also ensured that there are never more than 12 UITableViewCells allocated at any time, so those are re-used properly (the Cells are also created with an appropriate autorelease so they will be de-allocated when unused). I'm also pretty sure that I don't have any memory leaks built into the code of the corresponding UITableViewController.
Is this normal behavior, e.g. will the application release the memory it has claimed at a later time, maybe when it is needed somewhere else?
Cheers and thanks in advance
MrMage

Do you have NSZombieEnabled? I've seen this cause "incorrect" results in Instruments memory profiling since those instances will hang around.

Related

UIPickerView Causing leaks when connected via datasource

I created a test project to confirm my memory leaks:
Project file: https://dl.dropbox.com/u/3703182/PickerView.zip
Basically a UIPickerView is connected to a datasource via IB. When it's connected to a datasource, it leaks. If not, no leak. I need to use a UIPickerView for an imminent app that needs to be released ASAP, unfortunately it guarantees a crash every 2 hours because of the leak. How can I use the UIPickerView despite the memory leaks without crashing?
EDIT:
It only leaks on device, not in simulator.
That is not a leak. It's an allocation.
If it was a leak it would show a red spike in the second row.
The real test for a leak is presenting and dismissing several times over. If you can do that and show that the allocations keep rising then there is a leak. Not otherwise.
Adding my comments as answer,
Your app will not crash due to this leak since it is a very small leak caused by framework which you dont have to worry about. The screenshot shows that it is in terms of a few bytes. If your app is crashing every 2 hours, that means there is something else which is using a lot of memory. Please check if you are using anything else in your code which could cause this and update the question with your finding.
In allocation tool, make sure you are checking the live bytes section and check how much it is going up. If it stays below 15-20 MB, you dont have to worry much anyways. Check this for more details about memory usage in app. Also check this XCode Instruments Allocations: Look at Live Bytes or Overall Bytes?.
This is the Apple library that is leaking. You cannot do anything about this. It is Apple's fault.
This isn't a leak you can control, it's internal... but this is a very small amount of memory and will not crash your application. I'd be interested in seeing what this looks like an hour in... Can you provide a backtrace of the crash? That would probably better help determine the real cause of the crash.

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?

UIViews associated with memory leaks

My GUI for an iPhone app uses numerous UIViews. The user "flips" through these views when they tap a button to go forward or backward. The views are stored offscreen and are added to an actual view only when the program needs to display it.
During the flip process, the program tells the parent view (a uiscrollview) to remove any existing subview using the removeFromSuperView method, and then adds the new subview, which is the new page that the user should see.
However, after several repeats of this process on the device, the program crashes with gdb exit status 101, which I found is caused by an out of memory error.
I tried diagnosing this problem using the Leaks tool, but to no avail. There is only 1 or 2 small memory leaks and the total mem usage on the device by the program is only 2.5 mb. Is it possible that video memory, not system memory, is running low?
I came across this post regarding backgroundColor and mem usage, but I need further explanation. Should I reduce setting the backgroundColor to prevent the UIView's CALayer from hogging too much memory?
Do you have access to the iphone sample code on apple? Sounds like the PageControl Sample Code program is a good example of what you're looking for. And the sample code programs don't have memory leaks or any such problem :) Link here
When you were using instruments, did you check the ObjectAllocations? I've found that to be more useful than the leaks tool (object allocations is one of the tools leaks includes though). I would think that if video memory were running out it would be a different error, but I could be wrong.
Where are you storing all these views? Specifically, do you have some array (NSArray) that has these views when you flip through them?
The views won't get deallocated unless their reference count goes to zero. Your `[[UIView alloc] init] makes the reference count at 1, adding it as a subview makes it 2, and removing it from a subview makes it 1 again. Seeing as you don't get told of a specific leak, it seems that you're not really leaking as much as storing it somewhere.

Which memory is released by didReceiveMemoryWarning/viewDidUnload?

My iPhone application is running into problems when deployed to the device, principally because I haven't handled memory warnings thus far (no problem in the simulator, with 4GB of ram on my dev machine!). No problem there, I just need to handle these warnings more skilfully (less suckily...).
Question is, which memory does the runtime release... just the view and subviews? I suspect that it is just these, but want to be sure that the runtime will not dereference any of the objects or memory in my controller (ie. not in the view).
Subquestion: if it is just the view and subviews, do I need to do anything special in viewDidLoad to make sure that when the view is brought back into memory the view shows correct data, or is it all handled automatically via my IBOutlet-s?
There are potentially many things that the view, or its subviews, may cache - such as image data. These are the sort of things that will be purged.
Anything specific to your application that you can afford to flush you'll need to do yourself by handling that callback.
However, this may be more of an indication that you are either leaking memory or not being as efficient with it as you might be. It's certainly worth running the app in Instruments with the Leaks tool, as well as running with the CLANG compiler's static code analyser. Also, examine your code to see if you are holding on to blocks of memory you don't really need - whether you can compress images more etc.
Remember, before the 3GS or the latest iPod touch, system memory was 128Mb but you should only count on having about 25-30Mb available to your application
Neither viewDidUnload nor didRecieveMemoryWarning automatically release anything. You need to override both of these methods.
Generally, viewDidUnload should release anything in the view that wasn't created in IB, and that you can reasonably deal with reloading when the view is loaded up again.
And didRecieveMemoryWarning is a message that is sent to your app when the system is running low on memory. When your app receives this message, you should release anything and everything that you don't immediately need, or risk the system forcibly shutting down your app.