EXC_BAD_ACCESS Error Code

EXC_BAD_ACCESS Error

EXC_BAD_ACCESS means the app tried to access invalid or deallocated memory.

It is one of the most common and serious crashes in iOS/macOS development.

Typical crash:

text id=”m7q2we”
Thread 1: EXC_BAD_ACCESS (code=1, address=0x…)

Common causes in iOS (Objective-C)

  1. Accessing deallocated object

objectivec id=”v4k8ra”
NSObject *obj = [[NSObject alloc] init];
[obj release];
[obj description];

The object was already freed from memory.

  1. Dangling pointer

objectivec id=”n3p1xd”
NSString *str;
{
NSString *temp = [[NSString alloc] initWithString:@”Hello”];
str = temp;
[temp release];
}
NSLog(@”%@”, str);

  1. Over-releasing object (Non-ARC)

objectivec id=”u8w5kc”
[obj release];
[obj release];

Double release can crash.

  1. Invalid array access

objectivec id=”g7q2mv”
NSArray *arr = @[@”A”];
NSLog(@”%@”, arr[5]);

Usually causes:

text id=”r4k9zn”
NSRangeException

but may also lead to memory issues.

  1. Accessing zombie object

Message sent to deallocated instance.

Example:

text id=”t2p5xe”
message sent to deallocated instance

  1. Unsafe C pointers

objectivec id=”q6m3yt”
char *ptr = NULL;
printf(“%s”, ptr);

How to debug EXC_BAD_ACCESS

Enable Zombies

In Xcode:

Steps

  1. Product
  2. Scheme
  3. Edit Scheme
  4. Diagnostics
  5. Enable:

text id=”w9k1vc”
Zombie Objects

This helps identify deallocated objects.

Common fixes

Use ARC

Enable:

text id=”p4q7ra”
Automatic Reference Counting

ARC prevents:

  • over-release,
  • memory leaks,
  • dangling pointers. Use weak/strong properly Weak delegate

objectivec id=”j8m2kd”
@property (nonatomic, weak) id delegate;

Check object existence

objectivec id=”x5q7ne”
if(obj){
NSLog(@”%@”, obj);
}

Avoid manual memory management

If possible, avoid:

objectivec id=”f3k1wc”
retain
release
autorelease

under ARC projects.

Swift version

In Swift:

swift id=”b7p4xd”
unowned self

or unsafe pointers can also cause EXC_BAD_ACCESS.

Common crash messages

| Error | Meaning |
| — | – |
| message sent to deallocated instance | Object already freed |
| KERN_INVALID_ADDRESS | Invalid memory address |
| EXC_BAD_ACCESS code=1 | Bad memory access |
| SIGSEGV | Segmentation fault |

Useful tools

  1. Enable Zombies
  2. Add Exception Breakpoint
  3. Check stack trace
  4. Inspect object lifecycle
  5. Verify ARC settings Difference between SIGABRT and EXC_BAD_ACCESS

| Crash | Meaning |
| – | – |
| SIGABRT | App aborted due to exception |
| EXC_BAD_ACCESS | Invalid memory access |