[英]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 ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m 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. 具体来说,设置_board时,程序会在功能零中崩溃。 I would also like to point out that if you remove 我还要指出,如果您删除
[[A alloc] init];
from ViewController's implementation, the program doesn't crash. 从ViewController的实现中,程序不会崩溃。 Thanks for any help, in advance. 预先感谢您的帮助。
Make board
an ivar of class A and your problem should go away. 将board
设为A类的ivar,您的问题就应该解决了。 Right now it is a global, and the second [[A alloc] init];
现在,它是全局的,第二个[[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). 正在free
它(似乎您已启用ARC,并且llvm会看到该对象实际上并未被使用并立即释放它)。
When you invoke 调用时
[_gameBoard zero];
it is now trying to reference the free
'd global board
, which throws an EXC_BAD_ACCESS exception. 现在它正在尝试引用free
'd全局board
,该board
抛出EXC_BAD_ACCESS异常。
Globals like board
generally are a Bad Idea, as you have discovered. 正如您所发现的那样,像board
这样的全球人士通常不是一个好主意。
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. 首先,创建另一个A
实例并将其分配给变量没有任何意义。
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
). 但是主要的问题是您既不在ViewController
( _gameBoard
)上也没有在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. PS:您可能还想使用NSArray
而不是C样式的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.