Impact of Automatic Reference Counting (ARC) on Memory Leaks - iphone

I am new to iOS 5 and ARC, so pardon my silly question.
If we use ARC in our project, does it mean that there wont be any memory leaks at all.
Is there a need to use Instruments for detecting memory leaks and NSZombies if we use ARC?

ARC will help you eliminate certain types of leaks, because you won't forget to release or autorelease single objects. For example, this type of error becomes impossible:
myLabel.text = [[NSString alloc] initWithFormat:#"%d", 17];
// oops, just leaked that NSString!
However, ARC will not eliminate leaks caused by retain cycles. It's still up to you to eliminate retain cycles, either by using weak references or by manually breaking the cycles before they become leaked. For example, as we start to use blocks more, block/self retain cycles become much more common. The Transitioning to ARC Release Notes discuss how to avoid these cycles using weak references.

No, that does not prevent memory leaks from happening. What happens in runtimes with reference counting, is that sometimes your code leaves dangling references, and then objects are not freed. It's still up to you to write good code.

If we use ARC in our project, does it mean that there wont be any memory leaks at all.
There may still be leaks -- In your program, and in the libraries you use. As well, ARC only applies to ObjC objects - you can easily leak any heap allocation which is not an objc object (e.g. malloc/new).
Is there a need to use Instruments for detecting memory leaks and NSZombies if we use ARC?
Yes. The previous response should detail why your program is not guaranteed to be free of these problems. Also, the compiler can get it wrong if you do silly things, and you can certainly cause problems if don't protect your data properly (e.g. concurrent execution).

Related

Xcode Analyze 69 potential memory leaks

I'm making my first app and it's really confusing.
I am using ARC, and probably ALL of my potential leaks say:
"Object leaked: object allocated and stored in 'point' is not referenced later in this execution path and has a retain count of +1"
They are on almost any object I create using [[alloc] init].
Any suggestions about how to handle those? The app works fine, though.
Thanks.
Are you sure your project is actually set to ARC? Those types of analyzer warnings sound like it isn't. Is this a new project where ARC was automatically turned on for you or did you do the conversion for it yourself?
There isn't a way to actually tell the analyzer that you are ARC or aren't. It will just pick that up from the settings automatically.

How to exactly find where memory is leaking in project of iPhone

While developing apps in Xcode memory leaks are occurring. When I checked them in extended detail view they are showing different methods that are not related to implemented. How to exactly find out which object is leaking and where it is leaking memory.
When ARC is enabled we have to take care of memory leaks or not?
Even with ARC memory leaks can occur, it just inserts release and autorelease during compile time.
1. You must check for leaks using Build and analyze in XCode, shift+command+b you should be clearing those issues.
2. After that you can start using the instruments by using profile option command+i . This will point you to where the leak might be.
This link will help you too http://soulwithmobiletechnology.blogspot.in/2011/04/how-to-check-memory-leaks-in-xcode-4.html
Edit: Added some screenshots to hopefully make it clear.
During profiling after selecting leaks choose the call tree option and check the boxes hide system libraries , invert call tree and show obj-c only as shown in image below.
After double clicking the symbol name below you'll get the line where it is leaking.
You'll get something like this.
Yes, even with ARC there are memory leaks. ARC is not a garbage collector, it only inserts for you, at compile time, retains, releases and autoreleases in key positions. So although it does help the developer, you should be aware that memory leaks still exist (for instance circular referencing). You can start by using the Static Analyzer and correct any problem it shows you. You can then go to Instruments and choose Leaks.

Instruments is showing leaks for auto-released dictionaries, strings

Can't figure out what's going on here. +array and +dictionary are supposed to be autoreleased correct? Why then is instruments insisting I have memory leaks there?
So I set dictionaries for about 12 or so objects, and then eventually I set the property self.messageObjectsForPage = messageObjects;
Not sure what's happening here.
What I feel is that Instruments is not very precise yet on what it calls as Leaks.
I have been developing apps for more than an year now but I have faced similar issues many times.
Also you are correct that +array and +dictionary creates autoreleased objects.
So as far as the app works fine and doesn't give any memory warnings on device, you can ignore this minor leaks and search for other obvious leaks if they exist.
This is what Apple has to say about NSDictionary's +dictionary method
This method is declared primarily for use with mutable subclasses of NSDictionary.
If you don’t want a temporary object, you can also create an empty dictionary using alloc... and init.
So this assures that it is autoreleased object.
Hope this helps you.

NSAutoReleasePool appears not be working

I am writing an iPhone app that starts taking up memory as soon as it starts and just keeps taking up more memory. The reason appears to be that I've included a tight inner loop in that I'd like to run for a long while. Dont' worry, it's not supposed to be part of the user interactive app, it's just for testing the internal code.
In any case, by searching stackoverflow I found out that I should use my own NSAutoReleasePool because the main one is not getting reached. Also, I found that I should eschew use of autorelease. I've done both of these things, although I haven't been able to get rid of all autorelease calls. These do not fix the problem, however. Now my number of allocations (as per the instruments Allocations tool) travels in a triangle wave pattern, presumably because of the pool draining, but the number of allocations and the overall bytes creeps ever upwards. This increase in memory usage is also reflected in activity monitor. The objects that are getting allocated fall under all sorts of types including Malloc, CFString, NSConcreteMutableData; basically many core library classes and many of my code's objects.
This is basically what I'm doing:
for (int i=0; i<1000; i++) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
... do lots of stuff
[pool drain];
}
Any ideas why this is happening? I don't have any memory leaks according to the Leaks instrument and I don't have NSZombieEnabled set or any other arguments for that matter.
Thanks
UPDATE:
I just noticed some memory leaks are getting found when I use the auto release pool that aren't there when I'm not use the pool. Strange... Maybe that helps point towards the problem. I'm trying to track those leaks down now but so far they don't look like leaks in my code, but they make sense if the pool isn't actually releasing them.
UPDATE:
Ok, figured it out and it was caused by a few things. First, I was not properly releasing objects that contained references to each other so these never ended up getting released. Second, there are still memory leaks but these are in the foundation classes. I found an answer somewhere suggesting that this was not surprising, especially when running in the Simulator so I'm not going to worry about it too much. Hopefully this is useful to someone.
This can be caused by certain system caching, i.e. ImageNamed and certain URL calls will actually be cached by the system and are therefore not leaks but also nothing that you can release manually. There are normally better ways to handle such things for example creating your own image caching which you can clear...

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?