Tracking down EXC_BAD_ACCESS without NSZombie? - iphone

I've spent two days on this and I still can't find the cause of the crash.
I know it has something to do with trying to access an object that has been freed but I don't know which access or which object.
Whenever I google trying to find the source of EXC_BAD_ACCESS people suggest using NSZombies. The problem is when I enable zombies (either in xcode via environment variable or in instruments via ObjectAlloc properties) the program doesn't crash where it usually does and the zombies don't report anything (nothing shows up in logs and nothing is flagged in instruments). Is there something I'm missing with NSZombie?
I've tried utilizing some information from xcode's debugger and from ObjectAlloc in instruments but all the information is very cryptic and doesn't really help me.
I've set the debugger to stop on objective-c exceptions. When it does it this is the call stack shown:
0 objc_msgSend
1 ??
2 -[UITableViewCell removeFromSuperView]
3 -[UIView dealloc]
... etc ...
First of all, what's the deal with '1 ??' ? What do the question marks mean? Second of all how can I know where this was called in my code? All the operations stated are too generic (eg UIView dealloc, but which UIView? And where?).
Also when the exception occurs it points to assembly code which again, doesn't do me any good unless I was to spend hours trying to figure out what the code does. I know some assembly but there has to be a better way... right?
Is there any way I can get meaningful information as to what was the last line that ran in my code before the exception occurred?
I've tried sprinkling some NSLogs and breakpoints around but it doesn't help me much because the crash happens after I pop a view controller from a navigation controller. Everywhere I place breakpoints the breakpoints are reached fine (I can't find a point to break after the crash). It's only when I 'continue' in the debugger that the exception occurs. It's as if the crash happens outside of my code so I have no idea where to get a handle on it.
I've looked through my code and double checked that I adhere to all the memory management rules (at least to the best of my knowledge). I'm sure it's something very subtle but I can't seem to find it.
If anyone has any ideas how to find such bugs without NSZombie please share.
Thanks.

Well I found the problem. I had a custom table cell class in which I called [super dealloc] first in the dealloc method (rather than last). I guess I wrote this class in a hurry and didn't really think about it. I'm guessing something got released in the parent that the child needed for releasing?
So I don't have a real answer to my own question but basically I found the problem using a combination of ad-hoc code tracing and various debugging techniques (breakpoints, NSLogs, trying to decypher cryptic stack trace,etc).
Actually the main strategy that helped me was commenting out code bit by bit until I stripped down the problem area into as simple as it gets while still keeping the crash intact. This let me realize the problem wasn't where I thought it would be but in a more subtle area (eg in the dealloc method of a secondary class in this case).
I hope this can sort of help someone out. I'll leave this question unanswered for a bit incase someone has a more thorough debugging strategy without relying on NSZombies. Also if someone can clarify what those two question marks mean in the stack trace that would be helpful.

Related

UITextView delegates problem

I am trying to access the UITextView delegates and have a problem
I have a UIViewController with the UITextViewDelegate protocol and a Nib containing the textView.
If I set the delegate inside viewDidLoad like "textView.delegate = self" and I touch the textView, the app crashes without logging errors.
If I start editing the textView with code like "[textView becomeFirstResponder]" all delegates get called.
When I set the delegate in the Nib creating a connection between the textView and the File's owner and deleting "textView.delegate = self" also no delegates get called.
What am I doing wrong here?
Regards,
Elias
It's not easy to help you without more description, posted code or a xib file.
You say application crashes without any logging errors - well, do you mean that there's no output in console's window ? That is normal, for an app that has crashed.
Anyway, you should be able to get the stack-trace to figure out where approximately the application has crashed. Open the debugger (⇧⌘Y), and see the position. That should give you an idea of what went wrong.
Here you can see an example of such debugger session (after EXC_BAD_CRASH):
First two lines doesn't give us much information, but later on we can see that application has crashed while loading user interface from a NIB file. Well, usually the only code that executes during such load are awakeFromNib methods - it's up to you to find a problem along those lines.
Often top of code's execution doesn't make any sense - for example you might see your ViewController method somewhere, but the top few function calls (those where the code crashed) are located in methods/classes which you never call in your code. In most cases that is a sign of wrong memory de-/allocation. What might happened is that you forgot to retain some of your objects, it has already been released, but you are still keeping reference (a pointer) to its memory. Because that memory has been in fact freed, another object took its place later on, usually some Apple's internal object you've never heard about. Later on your code tries to message your poor object but it sends a message to something completely different. BUMMER! That's how you get those crashes and strange stack traces.
To fix the kind of problem I've just described you can use Instruments and its Zombies instrument. Unfortunately you can't start Zombies from within Xcode, you need to start Instruments standalone, then choose the Zombies under iPhone Simulator/Memory, then Choose Target from the toolbar, you should see your application in there, or be able to navigate to it on filesystem.
What Zombies instrument does is that it never really frees memory after objects are deallocated. Instead, it will mutate those objects into NSZombie class. That class intercepts all calls to itself, and informs you when some code is trying to send a message to it.
This is how such Instruments session looks like (this is the same crash as seen in debugger above):
In the table you can see that we're trying to message UIScrollView that has already been deallocated. You can as well see the whole history of retain/release calls to this particular object. That way you can find a missing retain or wrong release/autorelease.
Remember - Zombies Instruments can only be used with Simulator, because there's not enough memory on the real device to keep all those memory blocks.
Hopefully I could help you with further analysis of your problem.

Finding leaks under GeneralBlock-16?

If ObjectAlloc cannot deduce type information for the block, it uses 'GeneralBlock'. Any strategies to get leaks from this block that may eliminate the need of my 'trial and error' methods that I use? The Extended Detail thing doesn't really do it for me as I just keep guessing.
I find that sometimes if in the leaks instrument you click the button that looks something like this:
{= and drag your app delegate file onto the screen, it will lead you in the right direction by highlighting the code that allocated that leaked block.
Every time it goes into a function call drag the source file with that function onto it. This can be hit and miss though as sometimes these mystery leaks aren't tracked back to the delegate.
In XCode, you can try build and analyze. Sometimes it can be helpful in finding leaks and sometimes not. But it's worth a shot.
I've just started using objective-c and xcode (version 4) and it appears that by clicking on the leaked object in the memory profiler, you can see exactly the point in the code it is referring to in the "extended detail" pane. In here it shows you a stack trace and clicking on a point in the stack will take you to the exact point in the code where the leak is occuring. Not sure if this was available in v3. Hope this helps anyone else tracking down a leaky GeneralBlock-16.

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.

iPhone Bug App bug Question and challenge

Ok so I've got a really annoying bug in my app. It's driving me crazy and I'm sure it's beyond my skill level as I am learning as I go.
Here is the initial rundown of the bug: A shot in the dark - Application bug
However I have found a way to consistently reproduce the bug (only on the device not in the simulator)
First you create a new Pool and save it. Then add 20 blank time entires into one day. Save it and this is where the problems begin. (when you go back to the main detail view the tableview has put itself out of editing mode with being told to do so). Now if you go back to the day to see the time entries you just added they are still there.
If you go back to the main overall tableview listing all pools and now go back to the day you added the times they have dissapeared.
Add one time and it all saves fine. Add twenty and it doesn't save. WTF!!
Main Menu listing Pools:
Detail view:
Edit View:
Time Edit View:
Add a time:
I'd appreciate any more guesses. But as well as this question I'm offering a bounty of £25 (Sorry I'm a poor student) to whoever is good enough to fix this bug first!
if your interested my email is danmorgz[at]gmail.com
Thanks,
Dan
If you haven't already done so, I'd recommend turning on NSZombie support and seeing if you're using any of your objects after they've been freed. As far as I know this can be turned on in the simulator and on the device.
Most likely, you're failing to retain some object somewhere along the way. When an object gets released and then the memory is re-used for something else, you'll get all sorts of bad behavior, including crashes, or mysterious "disappearance" of other objects.
One thing you can try is putting breakpoints into the -dealloc method of your custom classes. Then you can see where they're getting deallocated from. Most likely though, this will end up being when the AutoreleasePool gets drained, which won't tell you much.
Alternatively, look into using some of the memory debugging tools built into Cocoa.
That document is for Mac OS X, but I think most all of this will work in the iPhone simulator, at least. I know that your bug "doesn't happen" in the simulator, but that really only means that the symptoms are different, and you're not noticing them.
Thanks for all your answers. It's now fixed.
For those interested I'd forgotten to add a cellidentifer in the XIB of my cell subclass.
cellForRow: method was therefore creating a new cell every time. The memory got filled up very quick. It then seemed as though my app was automatically trying to cut the fat by forcing another tableView out of editing mode and not managing my instances properly.
Again it's a memory problem. Isn't this always the case!?!
The clue was a one off 101 error in the console indicating my app was using too much memory. Oh and a slow scrolling tableView.

TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION error iPhone SDK development

I have a working program that was written by another programer that I am trying to add some features to in an effort to learn the iPhone SDK. I have carried out what I would assume was a fairly simple task of adding an additional UIButton to an existing view with like buttons. I have used the other UIButtons as a model and it seems this should be a simple task.
The problem is when the line that calls this subview is executed I get the rather vague error flag of TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION. Where do I find more information on this error code? I looks to me like a very general error and certianly there must be someplace in the Xcode shell that gives me more detail on what this means?
I have isolated the line where it occurs and it seems to happen on the first reference to the new view. Is it a problem with the connections made in interface builder? Any suggestions would be helpful as I really feel like I am grasping at straws at this point...
You want want to trap the exception when it happens, you might then be able to track it down in the debugger. A useful set of breakpoints to use when your debugging Cocoa apps are objc_exception_throw and -[NSException raise]. In the iPhone I think all exceptions travel through objc_exception_throw but if your were targetting Tiger or earlier you should set a breakpoint on both.
There are more debugging techniques at http://www.cocoadev.com/index.pl?DebuggingTechniques.
This is an exception generated by the Objective-C runtime. Hit CMD-SHIFT-R to bring up the debugger console. You'll see all the gdb startup information at the bottom of the window, but if you scroll up past the stack info, you'll get to something that should look like this:
[Session started at 2009-04-09 14:39:27 -0700.]
2009-04-09 14:39:31.246 LearnGLES[10415:20b] *** -[EAGLContext fakeMessage]: unrecognized selector sent to instance 0x528150
2009-04-09 14:39:31.248 LearnGLES[10415:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[EAGLContext fakeMessage]: unrecognized selector sent to instance 0x528150'
2009-04-09 14:39:31.250 LearnGLES[10415:20b] Stack: (
2517758219,
2486509115,
....
That's just a complete sample exception that I made up by changing code to send a non-existent message to an object, but there are a lot of possibilities as to what yours might be. Anything that would generate a run-time exception in any of the Objective-C frameworks could be the culprit (un-parseable dates to a date formatter, invalid messages to objects, etc...)
It probably means that you used some memory after deallocating it or used it without initializing it. Often when you look at the stack after this all you'll see is the part of the main loop that performs the autoreleases, which clearly isn't going to help you.
Really you need to get a good understanding of how memory management works in Objective-C and then take a look at your changes. There's not really a silver bullet here. The good news is that it gets easier with experience.
This is a nice article about debugging in Objective-C.
What connections have you made in interface builder? Are you making a call to any methods when the button is clicked? What is the method signature in that case? Have you made any changes to the original code, where you might have accidentally deleted some code which was important. It would help if you post some code. The exception is very generic.
I had a similar problem when I released things that I had not explicitly allocated.
In my case, I had a background image UIImage *image=[UIImage ...] and was setting it to be the background of my UIButton, and then did [image release];
You don't want to do the [image release]: the UIButton owns it now, and it will free it when no longer needed.
Maybe you have a similar issue?