简体   繁体   中英

iOS app crashes with EXC_BAD_ACCESS

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

Ah

#import <Foundation/Foundation.h>

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

Am

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

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 free ing 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM