tomKPZ
tomKPZ

Reputation: 837

iOS app crashes with EXC_BAD_ACCESS

I'm including the full project so nothing is ambiguous.

A.h

#import <Foundation/Foundation.h>

@interface A : NSObject
-(void) zero;
@end

A.m

#import "A.h"

@implementation A

#define width 3
#define height 3

uint8_t** _board;

-(void) zero
{
for(int i = 0; i < width; i++)
    for(int j = 0; j < height; j++)
        _board[i][j] = 0;
}

-(void)dealloc
{
for(int i = 0; i < width; i++)
    free(_board[i]);
free(_board);
}

-(id) init
{
self = [super init];
if(self)
{
    _board = malloc(sizeof(uint8_t*)*width);
    for(int i = 0; i < width; i++)
        _board[i] = malloc(sizeof(uint8_t)*height);
}
return self;
}

@end

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@end

ViewController.m

#import "ViewController.h"
#import "A.h"

@implementation ViewController

A* _gameBoard;

- (void)viewDidLoad
{
[super viewDidLoad];

_gameBoard = [[A alloc] init];
[[A alloc] init];

[_gameBoard zero];
}

@end

Specifically, the program crashes in the function zero when setting _board. I would also like to point out that if you remove

[[A alloc] init];

from ViewController's implementation, the program doesn't crash. Thanks for any help, in advance.

Upvotes: 0

Views: 247

Answers (2)

gschandler
gschandler

Reputation: 3208

Make board an ivar of class A and your problem should go away. Right now it is a global, and the second [[A alloc] init]; is freeing it (it appears you are ARC enabled, and llvm will see that the object is not actually being used and frees it immediately).

When you invoke

[_gameBoard zero];

it is now trying to reference the free'd global board, which throws an EXC_BAD_ACCESS exception.

Globals like board generally are a Bad Idea, as you have discovered.

Upvotes: 2

Marcelo
Marcelo

Reputation: 9944

You have several problems in your code. First of all, it doesn't make sense to create another A instance and not assign it to a variable.

The main problem though is that you're not using instance variables (or properties) neither on your ViewController (_gameBoard) nor on A (uint8_t** _board).

Making them instance variables (or properties) should fix your issue.

PS: You may want to use NSArray instead of C-style arrays also.

Upvotes: 1

Related Questions