问题
I have a class with the following init method:
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
StateStack* s = [[StateStack alloc] init];
state = s;
[s push:NONE]; //<--EXC_BAD_ACCESS on load here
[s release];
}
return self;
}
And StateStack has the following init code:
- (id)init {
self = [super init];
if (self) {
NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;
[s release];
NSLog(@"%d",[stack retainCount]);
}
return self;
}
Oddly, if I remove the NSLog line, the EXC_BAD_ACCESS moves to StateStack's dealloc method:
- (void)dealloc {
[stack release]; //<--EXC_BAD_ACCESS
[super dealloc];
}
Searching around seems to suggest that EXC_BAD_ACCESS is caused by overreleasing, but I can't see how I've overreleased anything. Does anyone know what the cause might be?
回答1:
In your init
function:
StateStack* s = [[StateStack alloc] init];
state = s;
[s push:NONE]; //<--EXC_BAD_ACCESS on load here
[s release];
you are allocating an instance of StateStack
; this gets a retain count of 1. Then at the end of the function you call release
, retain count goes to 0 and the object is ready to be released. So, when later dealloc
is executed, the state
ivar is sent another release
and that is causing the bad access. You don't need to release s, since you want that state be retained. The same error pattern occurs in the other init method.
This would be correct:
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
StateStack* s = [[StateStack alloc] init];
state = s;
[s push:NONE]; //<--EXC_BAD_ACCESS on load here
}
return self;
}
- (id)init {
self = [super init];
if (self) {
NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;
}
return self;
}
NB: I don't want to generate misunderstandings. Using retain count to check for correct memory allocation is useless. This is true. Anyway, reasoning in terms of retain count helps understanding what happens when you allocate/release/autorelease an object. It is the basic mechanism, but it is too difficult to track it usage to check for correctness of memory management.
回答2:
state = s
is not copying the NSMutableArray object, it's just copying the pointer to it. So when you call [s release]
the object referred to by both s and state is deallocated. You'll get an EXC_BAD_ACCESS whenever you use either from that point on.
Also, don't use [object retainCount]
to debug memory management problems. It lies. Google NSZombies.
回答3:
- (id)init{ self = [super init]; if (self) { // Initialization code here. state = [[StateStack alloc] init]; [state push:NONE]; } return self; }
StateStack
- (id)init { self = [super init]; if (self) { stack = [[NSMutableArray alloc] init]; } return self;
}
来源:https://stackoverflow.com/questions/6823053/finding-the-cause-of-exc-bad-access