Strange memory leak when calling SBJSON - iphone

I've been thoroughly testing my app using the Leaks tool in Instruments, and occasionally a leak comes up when using SBJSON. Having looked over the net it appears that SBJSON tends not to leak by itself, so it must be the way I am calling it. Here's a screenshot of the offending line in my code, pointed to by the Leaks instrument:
This leak is detected about 15 minutes into execution in this particular run, and is completely unpredictable in when it may happen. Instruments says the leaked memory is of type NSNumber, and this highlighted line is contained in a method that is called all the time throughout the execution of the app. I've tried outputting the value of the _source string to the console but there's nothing strange about the output when the leak occurs. Here's another screenshot showing the history of the leaked block:
I am running the app on the iPhone 4.2 simulator, and my testing basically involves clicking around every view in the application to make sure it all runs okay. As you may be able to see in the screenshot above, the JSONValue call goes to the method defined in NSString+SBJSON.m so I'm pretty sure if there is a problem it's in my code. Any idea what I am doing wrong?

When you assign _object = [[_source JSONValue] retain]; you increase reference count of object returned by JSONValue. In method initWithData:(NSData *)data this object is not released. So Analyzer thinks that there is memory leak.
You should check if you are releasing _object before losing reference to it or in dealloc method:
[_object release];

Related

Memory leak at performSelectorOnMainThread

I am running into some issues with the memory management on my app. The app will run properly for a while, then I will get a Received memory warning error. I then ran my app through Profile to find the memory leaks. After tracking the leaks, I got a 100% memory leak on this line:
[self performSelectorOnMainThread:#selector(loadingProgress:) withObject:[NSNumber numberWithFloat:0.0] waitUntilDone:NO];
I may be naive, but I didn't know that this could leak...
Anyone know how I can fix this?
The only possible leak is if you are over-retaining the NSNumber instance in your thread. But for that to cause a crash, you'd have to be spinning off thousands and thousands of threads, indicating a very serious problem in and of itself.
Note that the Leaks instrument shows you where the leak was allocated, not where it might have been over-retained.
Likewise, leaks only shows, well, leaks. It won't show accretion of allocations where the allocations are still referenced by the global object graph. I.e. if an object is reachable by a reference path starting at a global variable, then it isn't a leak.
Try heapshot analysis. It is very good at finding this kind of accretion over time.

Using Instruments for Memory Leak Checking in XCode?

Good Day,
I'm completely inexperienced in checking for memory leaks and so any help with this would be great.
I've just finished the bulk of the work for my iPhone app and I'm now trying to figure out why it stops working after a couple of runs. Using Instruments in Leaks and Allocations mode I can see there are two objects that are piling up memory quite quickly and not releasing:
I'm not a hundred percent sure where or why this is happening, but when I clicked on the arrow to the right of UIDeviceRGBColor the Responsible Caller is stated as
[UIColor allocWithZone];
I did a search through my project for UIColor and came up this (take note of _colorThreshold):
I believe my problem has to do with _colorThreshold which doesn't seem to be getting released:
I've tried adding autorelease to their initialisation arguments, but that made the app crash. Any advice here?
EDIT 1
Here is the screen shot from LevelMeter.h
There are several issues with the above:
Is LevelMeterColorThreshold an Objective-C class?
If so, why are you using malloc instead of the usual alloc/init?
As you pasted screenshots of your search results, we cannot see the surrounding code, as only lines with search hits are displayed.
Does the Leaks instrument report leaks, or are you just allocating unnecessary memory?
There is a difference between those two cases:
A leak happens if you loose reference to an object so that you cannot send it a release message later.
Instantiating objects, that aren't needed anymore without releasing/freeing them
Leaks can only detect the first case.
Sample for a leak:
NSMutableString* test = [[NSMutableString alloc] initWithString:#"1"];
NSLog(#"%#", test);
NSMutableString* anotherTest = [[NSMutableString alloc] initWithString:#"2"];
test = anotherTest; //here we loose reference to the original object
NSLog(#"%#", test);
By assigning anotherTest to test, we have lost the reference that points to the memory address that contains #"1".

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?

No leaks appearing in Instruments, even though I'm sure they exist

I'm checking for leaks in Instruments, and I've set to check every second, but no leaks are appearing.
I'm sure there must be some in my app, is there anything which could stop these from appearing? Is there a good way I can create a leak so that I can test if leaks do show up in Instruments?
Thanks!
Creating a leak is easy:
id someObject = [[NSObject alloc] init];
someObject = nil;
Drop some code like that into your app, and you should definitely see a leak show up in Instruments.
You're only going to find leaks with a tool if an object is allocated but no longer referenced. Another type of "leak" is to hold a reference to something that you didn't intend to. This typically happens with a collection like a hash table or a dictionary where key/value pairs get left in the collection that the programmer has forgotten about.
I'm pretty sure as clemahieu postulated, what you are really seeing are over-retained objects - you think you have freed them but they still are being retained.
One quick sanity check for this is to set breakpoints in dealloc and see if the classes you expect to be freed really are.
You can also use the memory tracking Instrument (not leaks) to see what memory is still around - just make sure to select the "created and still living" option to check out just what what objects are still around.

IPHONE: Analyzing leaks with instruments

I am trying to locate leaks using instruments, but the leaks I see there are like the ones in the next picture:
leaks
As you can see there's no information of which line of code is exactly leaking. All leaks I have, around 20, are like this, or in other words, the leaks don't show any line of my code in particular.
The leak in this picture is related to "_CFAllocatorSystem" (???) on the CoreFoundation and I have others that simply say GSEvent. I have no clue of what's generating these.
How can I discover that?
thanks for any help.
I think you want to go into instruments after running under leak and select "Source View". Then you need to drag your source files into the instrument window. It will then show the lines in the code where the leak occurs along with the call stack.
Some toss off code of mine leaks a view. It looks like this in Instruments:
alt text http://img688.imageshack.us/img688/9669/screenshot20091028at131.png
The thing that Leaks shows you is, the trace to the code that allocated the object that is leaking (which means it is retained but your application has no variables left that have that address). What it does not show you is just where the object should have been released to not cause the leak, for that is impossible to know (it is possible to find where release is currently being called, but that may not be so helpful).
So what this trace is telling me, is that some bit of memory allocated by the system is being retained by you, and then the reference forgotten - one key is the "PurpleEvent" line, which is common in a thread dealing with timer events or perhaps notifications. It could be you received a notification and kept something from it, without releasing it later on.
If you know about at what point the leak occurs, you should be able to isolate what code is running during that time.
See here and especially this quote:
This list informs you about the leaked objects' types, sizes, addresses, and even their call stacks.
Then you can trace the source of leaked memories through the call stacks.
The stack trace shows you exactly which line is the culprit. Apparently line 14 in main.m in your case. Dont know what you confused about?
The guilty was the accelerometer and I am compiling for OS 3.0.
In other words, the accelerometer that Apple said its leaks were fixed, is still leaking like hell.