[ios] EXC_BAD_ACCESS signal received

When deploying the application to the device, the program will quit after a few cycles with the following error:

Program received signal: "EXC_BAD_ACCESS".

The program runs without any issue on the iPhone simulator, it will also debug and run as long as I step through the instructions one at a time. As soon as I let it run again, I will hit the EXC_BAD_ACCESS signal.

In this particular case, it happened to be an error in the accelerometer code. It would not execute within the simulator, which is why it did not throw any errors. However, it would execute once deployed to the device.

Most of the answers to this question deal with the general EXC_BAD_ACCESS error, so I will leave this open as a catch-all for the dreaded Bad Access error.

EXC_BAD_ACCESS is typically thrown as the result of an illegal memory access. You can find more information in the answers below.

Have you encountered the EXC_BAD_ACCESS signal before, and how did you deal with it?

This question is related to ios cocoa-touch

The answer is


Don't forget the @ symbol when creating strings, treating C-strings as NSStrings will cause EXC_BAD_ACCESS.

Use this:

@"Some String"

Rather than this:

"Some String"

PS - typically when populating contents of an array with lots of records.


I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before: startPoint = [[DataPoint alloc] init] ; startPoint= [DataPointList objectAtIndex: 0];
. . . x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after: startPoint = [[DataPoint alloc] init] ; startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS


NSAssert() calls to validate method parameters is pretty handy for tracking down and avoiding passing nils as well.


I forgot to return self in an init-Method... ;)


This is an excellent thread. Here's my experience: I messed up with the retain/assign keyword on a property declaration. I said:

@property (nonatomic, assign) IBOutlet UISegmentedControl *choicesControl;
@property (nonatomic, assign) IBOutlet UISwitch *africaSwitch;
@property (nonatomic, assign) IBOutlet UISwitch *asiaSwitch;

where I should have said

@property (nonatomic, retain) IBOutlet UISegmentedControl *choicesControl;
@property (nonatomic, retain) IBOutlet UISwitch *africaSwitch;
@property (nonatomic, retain) IBOutlet UISwitch *asiaSwitch;

How To Debug EXC_BAD_ACCESS

Check out the link above and do as it says.... Just some quick instructions for using NSZombies

Run the application and after it fails (Should display "Interrupted" rather than "EXC_BAD_ACCESS"... check the Console (Run > Console)... there should be a message there now telling what object it was trying to access.

-Ben


Even another possibility: using blocks in queues, it might easily happen that you try to access an object in another queue, that has already been de-allocated at this time. Typically when you try to send something to the GUI. If your exception breakpoint is being set at a strange place, then this might be the cause.


Use the simple rule of "if you didn't allocate it or retain it, don't release it".


The 2010 WWDC videos are available to any participants in the apple developer program. There's a great video: "Session 311 - Advanced Memory Analysis with Instruments" that shows some examples of using zombies in instruments and debugging other memory problems.

For a link to the login page click HERE.


An EXC_BAD_ACCESS signal is the result of passing an invalid pointer to a system call. I got one just earlier today with a test program on OS X - I was passing an uninitialized variable to pthread_join(), which was due to an earlier typo.

I'm not familiar with iPhone development, but you should double-check all your buffer pointers that you're passing to system calls. Crank up your compiler's warning level all the way (with gcc, use the -Wall and -Wextra options). Enable as many diagnostics on the simulator/debugger as possible.


I realize this was asked some time ago, but after reading this thread, I found the solution for XCode 4.2: Product -> Edit Scheme -> Diagnostics Tab -> Enable Zombie Objects

Helped me find a message being sent to a deallocated object.


Not a complete answer, but one specific situation where I've received this is when trying to access an object that 'died' because I tried to use autorelease:

netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];

So for example, I was actually passing this as an object to 'notify' (registered it as a listener, observer, whatever idiom you like) but it had already died once the notification was sent and I'd get the EXC_BAD_ACCESS. Changing it to [[MyNetObject alloc] init] and releasing it later as appropriate solved the error.

Another reason this may happen is for example if you pass in an object and try to store it:

myObjectDefinedInHeader = aParameterObjectPassedIn;

Later when trying to access myObjectDefinedInHeader you may get into trouble. Using:

myObjectDefinedInHeader = [aParameterObjectPassedIn retain];

may be what you need. Of course these are just a couple of examples of what I've ran into and there are other reasons, but these can prove elusive so I mention them. Good luck!


In my case it was caused tableview delete operation. This solution solved my bad access exception: https://stackoverflow.com/a/4186786/538408


An EXC_BAD_ACCESS signal is the result of passing an invalid pointer to a system call. I got one just earlier today with a test program on OS X - I was passing an uninitialized variable to pthread_join(), which was due to an earlier typo.

I'm not familiar with iPhone development, but you should double-check all your buffer pointers that you're passing to system calls. Crank up your compiler's warning level all the way (with gcc, use the -Wall and -Wextra options). Enable as many diagnostics on the simulator/debugger as possible.


Just to add another situation where this can happen:

I had the code:

NSMutableString *string;
[string   appendWithFormat:@"foo"];

Obviously I had forgotten to allocate memory for the string:

NSMutableString *string = [[NSMutableString alloc] init];
[string   appendWithFormat:@"foo"];

fixes the problem.


Forgot to take out a non-alloc'd pointer from dealloc. I was getting the exc_bad_access on my rootView of a UINavigationController, but only sometimes. I assumed the problem was in the rootView because it was crashing halfway through its viewDidAppear{}. It turned out to only happen after I popped the view with the bad dealloc{} release, and that was it!

"EXC_BAD_ACCESS" [Switching to process 330] No memory available to program now: unsafe to call malloc

I thought it was a problem where I was trying to alloc... not where I was trying to release a non-alloc, D'oh!


How To Debug EXC_BAD_ACCESS

Check out the link above and do as it says.... Just some quick instructions for using NSZombies

Run the application and after it fails (Should display "Interrupted" rather than "EXC_BAD_ACCESS"... check the Console (Run > Console)... there should be a message there now telling what object it was trying to access.

-Ben


How i deal with EXC_BAD_ACCESS

Sometimes i feel that when a EXC_BAD_ACCESS error is thrown xcode will show the error in the main.m class giving no extra information of where the crash happens(Sometimes).

In those times we can set a Exceptional Breakpoint in Xcode so that when exception is caught a breakpoint will be placed and will directly intimate the user that crash has happened in that line

enter image description here


NSAssert() calls to validate method parameters is pretty handy for tracking down and avoiding passing nils as well.


Another method for catching EXC_BAD_ACCESS exceptions before they happen is the static analyzer, in XCode 4+.

Run the static analyzer with Product > Analyze (shift+cmd+B). Clicking on any messages generated by the analyzer will overlay a diagram on your source showing the sequence of retains/releases of the offending object.

enter image description here


Hope you're releasing the 'string' when you're done!


I encountered EXC_BAD_ACCESS on the iPhone only while trying to execute a C method that included a big array. The simulator was able to give me enough memory to run the code, but not the device (the array was a million characters, so it was a tad excessive!).

The EXC_BAD_ACCESS occurred just after entry point of the method, and had me confused for quite a while because it was nowhere near the array declaration.

Perhaps someone else might benefit from my couple of hours of hair-pulling.


NSAssert() calls to validate method parameters is pretty handy for tracking down and avoiding passing nils as well.


I just spent a couple hours tracking an EXC_BAD_ACCESS and found NSZombies and other env vars didn't seem to tell me anything.

For me, it was a stupid NSLog statement with format specifiers but no args passed.

NSLog(@"Some silly log message %@-%@");

Fixed by

NSLog(@"Some silly log message %@-%@", someObj1, someObj2);

Use the simple rule of "if you didn't allocate it or retain it, don't release it".


How i deal with EXC_BAD_ACCESS

Sometimes i feel that when a EXC_BAD_ACCESS error is thrown xcode will show the error in the main.m class giving no extra information of where the crash happens(Sometimes).

In those times we can set a Exceptional Breakpoint in Xcode so that when exception is caught a breakpoint will be placed and will directly intimate the user that crash has happened in that line

enter image description here


When you have infinite recursion, I think you can also have this error. This was a case for me.


I encountered EXC_BAD_ACCESS on the iPhone only while trying to execute a C method that included a big array. The simulator was able to give me enough memory to run the code, but not the device (the array was a million characters, so it was a tad excessive!).

The EXC_BAD_ACCESS occurred just after entry point of the method, and had me confused for quite a while because it was nowhere near the array declaration.

Perhaps someone else might benefit from my couple of hours of hair-pulling.


Before you do anything, you should try:

Product -> Clean

And run again. It worked for me. Otherwise, I would have wasted hours.


I find it useful to set a breakpoint on objc_exception_throw. That way the debugger should break when you get the EXC_BAD_ACCESS.

Instructions can be found here DebuggingTechniques


I just had this problem. For me the reason was deleting a CoreData managed object ans trying to read it afterwards from another place.


To check what the error might be

Use NSZombieEnabled.

To activate the NSZombieEnabled facility in your application:

Choose Project > Edit Active Executable to open the executable Info window. Click Arguments. Click the add (+) button in the “Variables to be set in the environment” section. Enter NSZombieEnabled in the Name column and YES in the Value column. Make sure that the checkmark for the NSZombieEnabled entry is selected.

I found this answer on iPhoneSDK


An EXC_BAD_ACCESS signal is the result of passing an invalid pointer to a system call. I got one just earlier today with a test program on OS X - I was passing an uninitialized variable to pthread_join(), which was due to an earlier typo.

I'm not familiar with iPhone development, but you should double-check all your buffer pointers that you're passing to system calls. Crank up your compiler's warning level all the way (with gcc, use the -Wall and -Wextra options). Enable as many diagnostics on the simulator/debugger as possible.


A major cause of EXC_BAD_ACCESS is from trying to access released objects.

To find out how to troubleshoot this, read this document: DebuggingAutoReleasePool

Even if you don't think you are "releasing auto-released objects", this will apply to you.

This method works extremely well. I use it all the time with great success!!

In summary, this explains how to use Cocoa's NSZombie debugging class and the command line "malloc_history" tool to find exactly what released object has been accessed in your code.

Sidenote:

Running Instruments and checking for leaks will not help troubleshoot EXC_BAD_ACCESS. I'm pretty sure memory leaks have nothing to do with EXC_BAD_ACCESS. The definition of a leak is an object that you no longer have access to, and you therefore cannot call it.

UPDATE: I now use Instruments to debug Leaks. From Xcode 4.2, choose Product->Profile and when Instruments launches, choose "Zombies".


NSAssert() calls to validate method parameters is pretty handy for tracking down and avoiding passing nils as well.


Not a complete answer, but one specific situation where I've received this is when trying to access an object that 'died' because I tried to use autorelease:

netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];

So for example, I was actually passing this as an object to 'notify' (registered it as a listener, observer, whatever idiom you like) but it had already died once the notification was sent and I'd get the EXC_BAD_ACCESS. Changing it to [[MyNetObject alloc] init] and releasing it later as appropriate solved the error.

Another reason this may happen is for example if you pass in an object and try to store it:

myObjectDefinedInHeader = aParameterObjectPassedIn;

Later when trying to access myObjectDefinedInHeader you may get into trouble. Using:

myObjectDefinedInHeader = [aParameterObjectPassedIn retain];

may be what you need. Of course these are just a couple of examples of what I've ran into and there are other reasons, but these can prove elusive so I mention them. Good luck!


I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before:

startPoint = [[DataPoint alloc] init] ;
startPoint= [DataPointList objectAtIndex: 0];
x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after:

startPoint = [[DataPoint alloc] init] ;
startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS

Thank you so much for your answer. I've been struggling with this problem all day. You're awesome!


Don't forget the @ symbol when creating strings, treating C-strings as NSStrings will cause EXC_BAD_ACCESS.

Use this:

@"Some String"

Rather than this:

"Some String"

PS - typically when populating contents of an array with lots of records.


This is an excellent thread. Here's my experience: I messed up with the retain/assign keyword on a property declaration. I said:

@property (nonatomic, assign) IBOutlet UISegmentedControl *choicesControl;
@property (nonatomic, assign) IBOutlet UISwitch *africaSwitch;
@property (nonatomic, assign) IBOutlet UISwitch *asiaSwitch;

where I should have said

@property (nonatomic, retain) IBOutlet UISegmentedControl *choicesControl;
@property (nonatomic, retain) IBOutlet UISwitch *africaSwitch;
@property (nonatomic, retain) IBOutlet UISwitch *asiaSwitch;

In my experience, this is generally caused by an illegal memory access. Check all pointers, especially object pointers, to make sure they're initialized. Make sure your MainWindow.xib file, if you're using one, is set up properly, with all the necessary connections.

If none of that on-paper checking turns anything up, and it doesn't happen when single-stepping, try to locate the error with NSLog() statements: sprinkle your code with them, moving them around until you isolate the line that's causing the error. Then set a breakpoint on that line and run your program. When you hit the breakpoint, examine all the variables, and the objects in them, to see if anything doesn't look like you expect.I'd especially keep an eye out for variables whose object class is something you didn't expect. If a variable is supposed to contain a UIWindow but it has an NSNotification in it instead, the same underlying code error could be manifesting itself in a different way when the debugger isn't in operation.


Just to add

Lynda.com has a fantastic DVD called

iPhone SDK Essential Training

and Chapter 6, Lesson 3 is all about EXEC_BAD_ACCESS and working with Zombies.

It was great for me to understand, not just the error code but how can I use Zombies to get more info on the released object.


I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before:

startPoint = [[DataPoint alloc] init] ;
startPoint= [DataPointList objectAtIndex: 0];
x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after:

startPoint = [[DataPoint alloc] init] ;
startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS

Thank you so much for your answer. I've been struggling with this problem all day. You're awesome!


To check what the error might be

Use NSZombieEnabled.

To activate the NSZombieEnabled facility in your application:

Choose Project > Edit Active Executable to open the executable Info window. Click Arguments. Click the add (+) button in the “Variables to be set in the environment” section. Enter NSZombieEnabled in the Name column and YES in the Value column. Make sure that the checkmark for the NSZombieEnabled entry is selected.

I found this answer on iPhoneSDK


The 2010 WWDC videos are available to any participants in the apple developer program. There's a great video: "Session 311 - Advanced Memory Analysis with Instruments" that shows some examples of using zombies in instruments and debugging other memory problems.

For a link to the login page click HERE.


Hope you're releasing the 'string' when you're done!


Even another possibility: using blocks in queues, it might easily happen that you try to access an object in another queue, that has already been de-allocated at this time. Typically when you try to send something to the GUI. If your exception breakpoint is being set at a strange place, then this might be the cause.


Just to add

Lynda.com has a fantastic DVD called

iPhone SDK Essential Training

and Chapter 6, Lesson 3 is all about EXEC_BAD_ACCESS and working with Zombies.

It was great for me to understand, not just the error code but how can I use Zombies to get more info on the released object.


In my experience, this is generally caused by an illegal memory access. Check all pointers, especially object pointers, to make sure they're initialized. Make sure your MainWindow.xib file, if you're using one, is set up properly, with all the necessary connections.

If none of that on-paper checking turns anything up, and it doesn't happen when single-stepping, try to locate the error with NSLog() statements: sprinkle your code with them, moving them around until you isolate the line that's causing the error. Then set a breakpoint on that line and run your program. When you hit the breakpoint, examine all the variables, and the objects in them, to see if anything doesn't look like you expect.I'd especially keep an eye out for variables whose object class is something you didn't expect. If a variable is supposed to contain a UIWindow but it has an NSNotification in it instead, the same underlying code error could be manifesting itself in a different way when the debugger isn't in operation.


I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before: startPoint = [[DataPoint alloc] init] ; startPoint= [DataPointList objectAtIndex: 0];
. . . x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after: startPoint = [[DataPoint alloc] init] ; startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS


Before you do anything, you should try:

Product -> Clean

And run again. It worked for me. Otherwise, I would have wasted hours.


I got it because I wasn't using[self performSegueWithIdentifier:sender:] and -(void) prepareForSegue:(UIstoryboardSegue *) right


In my case it was caused tableview delete operation. This solution solved my bad access exception: https://stackoverflow.com/a/4186786/538408


I find it useful to set a breakpoint on objc_exception_throw. That way the debugger should break when you get the EXC_BAD_ACCESS.

Instructions can be found here DebuggingTechniques


In my experience, this is generally caused by an illegal memory access. Check all pointers, especially object pointers, to make sure they're initialized. Make sure your MainWindow.xib file, if you're using one, is set up properly, with all the necessary connections.

If none of that on-paper checking turns anything up, and it doesn't happen when single-stepping, try to locate the error with NSLog() statements: sprinkle your code with them, moving them around until you isolate the line that's causing the error. Then set a breakpoint on that line and run your program. When you hit the breakpoint, examine all the variables, and the objects in them, to see if anything doesn't look like you expect.I'd especially keep an eye out for variables whose object class is something you didn't expect. If a variable is supposed to contain a UIWindow but it has an NSNotification in it instead, the same underlying code error could be manifesting itself in a different way when the debugger isn't in operation.


Just to add another situation where this can happen:

I had the code:

NSMutableString *string;
[string   appendWithFormat:@"foo"];

Obviously I had forgotten to allocate memory for the string:

NSMutableString *string = [[NSMutableString alloc] init];
[string   appendWithFormat:@"foo"];

fixes the problem.


Not a complete answer, but one specific situation where I've received this is when trying to access an object that 'died' because I tried to use autorelease:

netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];

So for example, I was actually passing this as an object to 'notify' (registered it as a listener, observer, whatever idiom you like) but it had already died once the notification was sent and I'd get the EXC_BAD_ACCESS. Changing it to [[MyNetObject alloc] init] and releasing it later as appropriate solved the error.

Another reason this may happen is for example if you pass in an object and try to store it:

myObjectDefinedInHeader = aParameterObjectPassedIn;

Later when trying to access myObjectDefinedInHeader you may get into trouble. Using:

myObjectDefinedInHeader = [aParameterObjectPassedIn retain];

may be what you need. Of course these are just a couple of examples of what I've ran into and there are other reasons, but these can prove elusive so I mention them. Good luck!


A major cause of EXC_BAD_ACCESS is from trying to access released objects.

To find out how to troubleshoot this, read this document: DebuggingAutoReleasePool

Even if you don't think you are "releasing auto-released objects", this will apply to you.

This method works extremely well. I use it all the time with great success!!

In summary, this explains how to use Cocoa's NSZombie debugging class and the command line "malloc_history" tool to find exactly what released object has been accessed in your code.

Sidenote:

Running Instruments and checking for leaks will not help troubleshoot EXC_BAD_ACCESS. I'm pretty sure memory leaks have nothing to do with EXC_BAD_ACCESS. The definition of a leak is an object that you no longer have access to, and you therefore cannot call it.

UPDATE: I now use Instruments to debug Leaks. From Xcode 4.2, choose Product->Profile and when Instruments launches, choose "Zombies".


XCode 4 and above, it has been made really simple with Instruments. Just run Zombies in Instruments. This tutorial explains it well: debugging exc_bad_access error xcode instruments


Another method for catching EXC_BAD_ACCESS exceptions before they happen is the static analyzer, in XCode 4+.

Run the static analyzer with Product > Analyze (shift+cmd+B). Clicking on any messages generated by the analyzer will overlay a diagram on your source showing the sequence of retains/releases of the offending object.

enter image description here


I realize this was asked some time ago, but after reading this thread, I found the solution for XCode 4.2: Product -> Edit Scheme -> Diagnostics Tab -> Enable Zombie Objects

Helped me find a message being sent to a deallocated object.


I just had this problem. For me the reason was deleting a CoreData managed object ans trying to read it afterwards from another place.


In my experience, this is generally caused by an illegal memory access. Check all pointers, especially object pointers, to make sure they're initialized. Make sure your MainWindow.xib file, if you're using one, is set up properly, with all the necessary connections.

If none of that on-paper checking turns anything up, and it doesn't happen when single-stepping, try to locate the error with NSLog() statements: sprinkle your code with them, moving them around until you isolate the line that's causing the error. Then set a breakpoint on that line and run your program. When you hit the breakpoint, examine all the variables, and the objects in them, to see if anything doesn't look like you expect.I'd especially keep an eye out for variables whose object class is something you didn't expect. If a variable is supposed to contain a UIWindow but it has an NSNotification in it instead, the same underlying code error could be manifesting itself in a different way when the debugger isn't in operation.


Not a complete answer, but one specific situation where I've received this is when trying to access an object that 'died' because I tried to use autorelease:

netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];

So for example, I was actually passing this as an object to 'notify' (registered it as a listener, observer, whatever idiom you like) but it had already died once the notification was sent and I'd get the EXC_BAD_ACCESS. Changing it to [[MyNetObject alloc] init] and releasing it later as appropriate solved the error.

Another reason this may happen is for example if you pass in an object and try to store it:

myObjectDefinedInHeader = aParameterObjectPassedIn;

Later when trying to access myObjectDefinedInHeader you may get into trouble. Using:

myObjectDefinedInHeader = [aParameterObjectPassedIn retain];

may be what you need. Of course these are just a couple of examples of what I've ran into and there are other reasons, but these can prove elusive so I mention them. Good luck!


I just spent a couple hours tracking an EXC_BAD_ACCESS and found NSZombies and other env vars didn't seem to tell me anything.

For me, it was a stupid NSLog statement with format specifiers but no args passed.

NSLog(@"Some silly log message %@-%@");

Fixed by

NSLog(@"Some silly log message %@-%@", someObj1, someObj2);

XCode 4 and above, it has been made really simple with Instruments. Just run Zombies in Instruments. This tutorial explains it well: debugging exc_bad_access error xcode instruments


Forgot to take out a non-alloc'd pointer from dealloc. I was getting the exc_bad_access on my rootView of a UINavigationController, but only sometimes. I assumed the problem was in the rootView because it was crashing halfway through its viewDidAppear{}. It turned out to only happen after I popped the view with the bad dealloc{} release, and that was it!

"EXC_BAD_ACCESS" [Switching to process 330] No memory available to program now: unsafe to call malloc

I thought it was a problem where I was trying to alloc... not where I was trying to release a non-alloc, D'oh!


When you have infinite recursion, I think you can also have this error. This was a case for me.


I got it because I wasn't using[self performSegueWithIdentifier:sender:] and -(void) prepareForSegue:(UIstoryboardSegue *) right


An EXC_BAD_ACCESS signal is the result of passing an invalid pointer to a system call. I got one just earlier today with a test program on OS X - I was passing an uninitialized variable to pthread_join(), which was due to an earlier typo.

I'm not familiar with iPhone development, but you should double-check all your buffer pointers that you're passing to system calls. Crank up your compiler's warning level all the way (with gcc, use the -Wall and -Wextra options). Enable as many diagnostics on the simulator/debugger as possible.


I forgot to return self in an init-Method... ;)