298

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?

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
Héctor Ramos
  • 9,239
  • 6
  • 36
  • 39

36 Answers36

201

From your description I suspect the most likely explanation is that you have some error in your memory management. You said you've been working on iPhone development for a few weeks, but not whether you are experienced with Objective C in general. If you've come from another background it can take a little while before you really internalise the memory management rules - unless you make a big point of it.

Remember, anything you get from an allocation function (usually the static alloc method, but there are a few others), or a copy method, you own the memory too and must release it when you are done.

But if you get something back from just about anything else including factory methods (e.g. [NSString stringWithFormat]) then you'll have an autorelease reference, which means it could be released at some time in the future by other code - so it is vital that if you need to keep it around beyond the immediate function that you retain it. If you don't, the memory may remain allocated while you are using it, or be released but coincidentally still valid, during your emulator testing, but is more likely to be released and show up as bad access errors when running on the device.

The best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
philsquared
  • 22,403
  • 12
  • 69
  • 98
  • 2
    I had some accelerometer sampling code that was not vital to my app, which after removal, eliminated the bad access error. Which makes sense considering the simulator does not have an accelerometer. I do find it weird that this code existed, untouched, for a week before causing this error... – Héctor Ramos Nov 30 '08 at 00:31
  • I am new to Objective-C so most of my problems should arise from memory management. After a few years in C++, I've been using mostly Java for the last three or four years so I've gotten rusty on memory management. Thanks for your answer! – Héctor Ramos Nov 30 '08 at 00:32
  • 4
    No problem - glad you fixed it. The memory management is not really hard to get on top of - you just need make sure you learn the rules and get into good habits. – philsquared Nov 30 '08 at 01:14
  • The problem I've had seems to be exclusively with being too aggressive in releasing strings (and such) that I create. I'm still not 100% sure on what should be released and when, but Phil's answer certainly helped. – pluckyglen May 26 '09 at 04:37
  • If I followed that correctly, cmculloh, yes that was the right thing to do. You do not own the object return from objectAtIndex. – philsquared Sep 11 '09 at 12:17
102

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".

xverges
  • 4,608
  • 1
  • 39
  • 60
bentford
  • 33,038
  • 7
  • 61
  • 57
  • 18
    That sidenote is very important. Leaks can't cause EXC_BAD_ACCESS (they have other problems). I wrote this to try to clear up misconceptions about EXC_BAD_ACCESS http://loufranco.com/blog/files/Understanding-EXC_BAD_ACCESS.html – Lou Franco Jul 23 '10 at 11:57
  • 4
    That zombies tool in Xcode is brilliant! I found the culprit in 3 min not hours. – Aram Kocharyan Mar 02 '12 at 04:50
  • 1
    above link in answer in not available. Shows 404 not found error. – Tejas Jan 03 '17 at 12:00
  • Looks like it's this one https://cocoadev.github.io/DebuggingAutorelease/ – Morten J May 21 '21 at 16:05
13

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.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
8

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.

Becca Royal-Gordon
  • 17,541
  • 7
  • 56
  • 91
7

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);
Scott Heaberlin
  • 3,364
  • 1
  • 23
  • 22
  • I feel your pain. I spent hours thinking it had to be my latest code entries only to find some earlier hack had came back to bite me. – leerie simpson Mar 12 '21 at 14:01
7

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.

Jonah
  • 4,810
  • 14
  • 63
  • 76
6

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

benhameen
  • 1,418
  • 15
  • 24
lyonanderson
  • 2,035
  • 14
  • 14
6

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!

logancautrell
  • 8,762
  • 3
  • 39
  • 50
Rob
  • 4,093
  • 5
  • 44
  • 54
5

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.

gnuchu
  • 1,496
  • 13
  • 21
  • This doesn't cause any error for me because string gets initialized to nil and using the null object pattern calling a method on nil does nothing. – Liron Yahdav Nov 14 '14 at 18:28
5

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

ericsoco
  • 24,913
  • 29
  • 97
  • 127
4

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

Gamma-Point
  • 1,514
  • 13
  • 14
4

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ben Call
  • 976
  • 1
  • 10
  • 16
3

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

3

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

ipraba
  • 16,485
  • 4
  • 59
  • 58
3

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

denbec
  • 1,321
  • 18
  • 25
3

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!

logancautrell
  • 8,762
  • 3
  • 39
  • 50
Josh
  • 31
  • 1
3

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;
fool4jesus
  • 2,147
  • 3
  • 23
  • 34
  • 1
    Strange, why would you need to retain IBOutlet? Their management is done for you automagically. – jv42 Jan 13 '11 at 16:09
3

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.

mblackwell8
  • 3,065
  • 3
  • 21
  • 23
3

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

  • I made similar mistake. I forgot to reain the instance which caused crash and I spent hours to figure it out. Your experience lit me to find out mine. Thanks! – David.Chu.ca Apr 12 '10 at 04:19
2

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

konryd
  • 541
  • 1
  • 5
  • 12
2

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

coolcool1994
  • 3,704
  • 4
  • 39
  • 43
2

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.

balexandre
  • 73,608
  • 45
  • 233
  • 342
2

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

Ryan Townshend
  • 2,404
  • 21
  • 36
2

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

zambono
  • 1,397
  • 1
  • 17
  • 26
2

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.

Sean Aitken
  • 1,177
  • 1
  • 11
  • 23
2

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!

  • 4
    Aren't you just immediately overwriting startPoint? I don't think you need that first line at all. – toxaq Sep 24 '10 at 05:36
  • 2
    There is absolutely no need to allocate and initialise a variable if you're immediately going to overwrite it with another. You're just leaking the object in the first assignment. – dreamlax Oct 19 '10 at 20:35
1

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.

Girish
  • 4,692
  • 4
  • 35
  • 55
Artur
  • 1,125
  • 11
  • 17
1

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.

brainray
  • 12,512
  • 11
  • 67
  • 116
1

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

DHShah01
  • 553
  • 1
  • 7
  • 16
1

Before you do anything, you should try:

Product -> Clean

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

rghome
  • 8,529
  • 8
  • 43
  • 62
1

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

NANNAV
  • 4,875
  • 4
  • 32
  • 50
Rons Micheal
  • 179
  • 1
  • 6
0

In my case i had a view (A) which in i had an instance of another view (B). i had forgotten that B was subclassed from A. Obviously this leads to a recursive and endless allocation. breaking this issue fixed the EXE_BAD_ACCESS problem.

   class A: UIView {
 
      let b = B()
      .
      .
   }



   class B: A {
     .
     .
   }
Mehrdad
  • 1,050
  • 1
  • 16
  • 27
0

EXC_BAD_ACCESS

EXC_BAD_ACCESS accessing to an object that has already been released. Kernel sends this exception(EXC), saying that block of memory cannot be accessed(BAD ACCESS).

  • [unowned(unsafe)] is used
  • when one target uses another target with different IPHONEOS_DEPLOYMENT_TARGET[About]. In my case Test target(10.0) used explicit dependency[About] with 14.0 IPHONEOS_DEPLOYMENT_TARGET
yoAlex5
  • 29,217
  • 8
  • 193
  • 205
0

EXC_BAD_ACCESS error when trying to allocate ScrollView space of 140000xScreen Height on 12 Pro Max. It allocates fine until it reach around 140,000 pixel width. ;)

jonkimsr
  • 31
  • 1
  • 6
0

If you are using custom fonts and you are instantiate them programmatically, this error can occur if you not register the fonts in runtime previously.

To be sure if is the case, the Xcode console will print something like this:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1d8)
    frame #0: 0x0000000180f969cc CoreText`CTFontGetClientObject + 12
...

or

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    frame #0: 0x000000012341c10e CoreFoundation`CFRelease.cold.1 + 14
    frame #1: 0x00000001232ed7bd CoreFoundation`CFRelease + 77
    frame #2: 0x0000000128136990 libGSFont.dylib`GSFontGetExtraData + 112
    frame #3: 0x0000000135bc8958 UIFoundation`-[UIFont lineHeight] + 9
    frame #4: 0x00000001340149f3 UIKitCore`-[UILabel intrinsicContentSize] + 331
...

To register the custom fonts and solve that issue, you can checkout this solution: https://stackoverflow.com/a/69756114/3701102

pableiros
  • 14,932
  • 12
  • 99
  • 105
-1

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

Community
  • 1
  • 1
Murat
  • 3,084
  • 37
  • 55