sometimes crash EXC_BAD_ACCESS with no message (set NSZombieEnabled) - iphone

I'm handling RemoteIO to get mic inputs and modify them little.
Sometimes it crashes with EXC_BAD_ACCESS and there is no more message.
The lines that make crashes are these;
int currPower = [[powers objectAtIndex:i] intValue];
int prevPower = [[powers objectAtIndex:i - 1] intValue];
explaining the code,
"powers" is NSMutableArray.
[powers count] was always bigger than variable "i"
Struggling for a while, I found a good way to fix it.
A environment variables.
So I set NSZombieEnabled and also NSDebugEnabled so that I could see the reason of the crashes.
But even though I set the variables, Xcode shows no message.
(But it correctly shows messages when a crash occurs from other line.)
Also a weird thing is that it doesn't crash just after the start of run;
it crashes in a minute in average. (But the times really varied.)
And this is a little guess. When I decreased the rate to half than before,
it was more stable.
So, is it a problem with NSMutableArray, because NSMutableArray method couldn't catch up the speed of the rate?
or do you see some other possible reasons?
=========================================================================================
There are some more codes.
I allocated powers in this way..
powers = [[NSMutableArray alloc] initWithCapacity:POWER_ARRAY_SIZE];
where I release the powers array is..
- (void)dealloc {
[powers release];
[super dealloc];
}
and no where else.
more detailed code is this.
- (void)drawRect:(CGRect)rect
{
...//Do Something
...//Check "endindex" and "startindex" not to exceed boundary
for (int i = endindex; i > startindex; i-=1)
{
int currPower = [[powers objectAtIndex:i] intValue];
int prevPower = [[powers objectAtIndex:i - 1] intValue];
...//Doing something
}
}
this drawRect: method is calling from Main Thread(By Timer) in every millisecond.
--
updating(more specifically adding) powers in this method
- (void)setPower:(int)p
{
[powers addObject:[NSNumber numberWithInt:p]];
while ([powers count] > POWER_ARRAY_SIZE){
[powers removeObjectAtIndex:0];
}
}
and also this method is calling in every millisecond.
and this is calling in background thread.
so without #autoreleasepool XCode Shows message of alert of leaking
for this reason I blocked the method(setPower) with #autoreleasepool{..}

If NSZombies solved your problem it means that your NSMutableArray is being released somewhere, or it's in an autorelease pool. Also you could be trying to write outside the bounds of your array.
If the NSMutableArray is in an autorelease pool (it was created by a convenience method or you explicitly autoreleased it) manually retain it and release it when you no longer need it.
If the object is not in an autorelease pool check when the release is called for that object.
Write a simple warning before the assignment:
if( i <= 0 || i >= [powers count] ) NSLog(#"Here's the problem. i = %d", i);

I found the answer.
Crashes are occurred because NSMutableArray of objected-C sometimes ack wrong.
That's when I try to do something in every milliseconds with it.
So I changed the Objective-C array to C array, like
int power[ARRAYSIZE];
and after I changed it, it works fine.
May be NSMutableArray isn't that light to do something really fast.

Related

NSMutableArray memory leaks in recursive method

I have a recursive method that allocates an NSMutableArray, runs a recursive call and then releases the NSMutableArray. the method takes an array of numbers and a target value and then finds what combinations of the numbers can sum up to equal the target value e.g. target: 10, numbers: 5,5,4. the method returns an array of NSNumbers 5 and 5.
My problem is that a mutable array is always showing as a leak in the leaks instrument even though i am releasing it.
here is the recursive method:
-(NSMutableArray *) getCombsHelper:(NSArray *)numbers target:(int)target partial:(NSMutableArray *)partial {
int s = 0;
for (NSNumber *number in partial) {
s += [number intValue];
}
if (s == target)
[results addObject:partial];
if (s >= target)
return results;
for (int i = 0; i < [numbers count]; i++) {
NSMutableArray *remaining = [[[NSMutableArray alloc] init] autorelease];
int n = [[numbers objectAtIndex:i] intValue];
for (int j = i+1; j<[numbers count]; j++) {
[remaining addObject:[numbers objectAtIndex:j]];
}
//this is the array that is showing up as a leak.
NSMutableArray *partialRec = [[NSMutableArray alloc] initWithArray:partial];
[partialRec addObject:[NSNumber numberWithInt:n]];
[self getCombsHelper:remaining target:target partial:partialRec];
[partialRec release]; //the mutable array is released after the recursive call.
}
return results;
}
even if i autorelease it i am still getting it as a leak. Could this be a false positive leak? or is there something wrong i cant catch?
That method is odd;
results appears to be an instance variable that accumulate the results? That is generally odd; typically, you'll have something that calculates state into an ivar and a plain accessor that retrieves the ivar.
To expand: your recursive method is relatively expensive compared to a straight getter method. Say you need results in three places; if this recursive method is the only way to retrieve results, every call will incur calculation overhead. If, instead, you had something like:
- (void)combsHelper:...
- (NSArray*) results
{
return results;
}
Then you could do the calculation once and retrieve the results many times without incurring overhead (while you could do something like if (!results) [self combsHelper:...] in your getter, that'll lead to the getter causing mutation of state which is generally to be avoided -- best to separate the two).
don't name methods getSomething:...; get as a prefix is limited to a very specific use pattern (generally, pass by reference retrieval of a value -- uncommon)..
What array is leaking? Keep in mind that Instruments shows you the point of allocation of the leak, not where the real leak happens. If something is retaining the object elsewhere without a balanced release, that'll be your leak.
The leak is outside of this method; partialRec is being added to the results array. Something is probably retrieving it from said array, retaining it, and not balancing that with a release
Perhaps the complaint is that you pass partialRec to the method, then add it to an array (results), which you return, but you don't catch your return value.
Adding it to the array will retain it.
Where does 'results' come from anyway? I don't see its declaration.
You probably have a problem on this line:
[self getCombsHelper:remaining target:target partial:partialRec];
You are passing partialRec to another method, and it is not autoreleased.

EXC_BAD_ACCESS in iPhone app - memory management issue

For reference, I've already read:
memory management question -- releasing an object which has to be returned
iPhone: Return NSMutableArray in method while still releasing
Releasing objects returned by method
Which I thought would help :).
This app is a teaching tool and is intended to help people visualize simple genetics. Just some background so the variable names and stuff will make sense. Here's the main code that executes when the app runs:
- (void)viewDidAppear:(BOOL)animated {
ThingzCore *core = [[ThingzCore alloc] init];
ThingzThing *thing1 = [[ThingzThing alloc] init];
thing1.breed = #"AB";
thing1.pattern = #"AC";
thing1.color = #"CA";
thing1.gender = #"XY";
thing1.generation = 1;
thing1.isEgg = NO;
ThingzThing *thing2 = [[ThingzThing alloc] init];
thing2.breed = #"CD";
thing2.pattern = #"BA";
thing2.color = #"CB";
thing2.gender = #"XX";
thing2.generation = 1;
thing2.isEgg = NO;
NSLog(#"Breeding GD BR PT CL G");
ThingzThing *child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 1: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 2: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 3: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
child = [core mateFather:thing1 withMother:thing2];
NSLog(#"Round 4: %# %# %# %# %d",child.gender,child.breed,child.pattern,child.color,child.generation);
sleep(10);
[thing1 release];
[thing2 release];
[core release];
}
And here's what happens when I run it in various ways:
Running without breakpoints, it crashes, with no console message, after the 2nd sleep() but before the "Round 3" NSLog.
Running with breakpoints enabled, but none defined, it runs through the entire sequence. After the fourth sleep(), it crashes with EXC_BAD_ACCESS.
Running with breakpoints enabled and NSZombiesEnabled, it does the same thing as above - no further information, just EXC_BAD_ACCESS.
Running in Instruments, no leaks are shown.
This is the routine being called four times:
-(ThingzThing *)mateFather:(ThingzThing *)father
withMother:(ThingzThing *)mother {
// will we be doing a mutation?
int mutationPercentage = father.generation + mother.generation;
int mutationNumber = (arc4random() % ((unsigned)100 + 1));
BOOL isMutation = NO;
if (mutationNumber <= mutationPercentage) {
isMutation = YES;
}
// get possibilities
NSArray *possibilities = [self possibilitiesByMatingFather:father
withMother:mother
mutations:isMutation];
// randomly select one of the possibilities
int keeping = (arc4random() % ((unsigned)[possibilities count]));
return [possibilities objectAtIndex:keeping];
}
Without pasting in the ENTIRE code, the possibilitiesByMatingFather:withMother:mutations function is returning an NSMutableArray. That routine declares the array by using:
NSMutableArray *possibilities = [NSMutableArray array];
It then:
return possibilities;
It does not send a release or autorelease message to possibilities; my understanding is that creating the array the way I have is an implicit autorelease. I didn't want to alloc the array, because I'm returning it, so wouldn't have the opportunity to explicitly release it.
The objects held in the possibilities NSMutableArray are of a custom class. They are added as follows:
ThingzThing *newThing = [[ThingzThing alloc] init];
newThing.breed = choiceBreed;
newThing.gender = choiceGender;
newThing.color = choiceColor;
newThing.pattern = choicePattern;
newThing.generation = mother.generation + father.generation;
newThing.name = #"";
newThing.isEgg = YES;
[possibilities addObject:newThing];
[newThing release];
Which seems to work most of the time. At least, when breakpoints are enabled, the program runs through the code without complaint until the end, as noted above.
Any suggestions on what I'm doing wrong, here? It's obviously memory management issues of some kind, but I can't sort it in my head.
BTW, in a vain, throwing-things-at-the-wall attempt to figure it out, I did modify the one line from the main routine as follows:
// get possibilities
NSArray *possibilities = [[self possibilitiesByMatingFather:father
withMother:mother
mutations:isMutation] retain];
To no avail. Same results. So the problem isn't in retaining the array returned by possibilitiesByMatingFather:withMother:mutations. Forcing a retain on that return isn't helping.
Frequently in this type of situation, the actual error is not at the location shown in the debugger when the app halts.
For example, the debugger may be pointing to a method call, but the problem actually occurs inside the method -- not when the method is called.
To track things down, I would suggest setting a breakpoint just before the method call that triggers the error -- in your case, this would be the mateFather: withMother: call. Then step into that method. There is a good chance you will find that the problem happens inside that method -- or even inside a method called from within that method.
Check you have the correct property declarations of the string properties of class ThingzThing.
e.g.
#property (nonatomic, retain) NSString* breed;
NEED to be retain or copy NOT assign...
Found it. Buried eight method calls down, I was sending release to an NSArray that was obviously autoreleasing. When the initial calling routine (viewDidAppear) fell down into autorelease mode, it tried to autorelease the already-released object, and exploded. Good grief - is there any way XCode could have helped me track that down?
In any event, in case anyone runs across this, make bloody sure you're not sending a release message to something that you didn't explicitly alloc yourself. If you didn't alloc it, odds are it was autoreleasing itself, and you sending a release to it takes the retain count negative, and the Foundation framework vomits with an EXC_BAD_ACCESS.

EXC_BAD_ACCESS when setting ivars directly (without using accessors) inside -init method, why?

I've spent about 10 hours trying to find this bug that was causing my app to crash, and it was in the last place I looked (well it would have been, but last place I ever expected it to be).
Originally I thought I had memory management issues (unbalanced retain/release) because the crash would happen every time I sent -removeAllObjects to an NSMutableArray filled with my custom objects. The crash wouldn't happen the first time -removeAllObjects was called. I could clear the array once, repopulate it, and then on the second clear, I would get a EXC_BAD_ACCESS. This is when my array got populated with 3 objects on the first "cycle", and 3 again on the second "cycle". When I was storing only 1 object in the array in each cycle it took 4 cycles to crash (on the 4th call of -removeAllObjects).
I FINALLY realised that the crash would go away if I changed the -init method of my custom object. Here's the -init implementation; all 4 ivars are synthesized properties with (nonatomic, retain), all of type (NSString *) except for icon which is an (NSNUmber *)
-(id)init {
if (self = [super init]) {
ip = #"";
mac = #"";
vendor = #"";
icon = [NSNumber numberWithInt:0];
}
return self;
}
Changing it to this fixed the bug:
-(id)init {
if (self = [super init]) {
self.ip = #"";
self.mac = #"";
self.vendor = #"";
self.icon = [NSNumber numberWithInt:0];
}
return self;
}
I've read that one should't use the accessors in the -init method because it can cause trouble (e.g. with subclassing).
If someone could explain to me why my bug goes away when I use accessors I would be so incredibly grateful! Seriously this has been driving me nuts, was up till 5am last night because of this.
You are assigning, but not retaining, the instance variables directly. When you use the dot syntax, you are triggering the retain part of the synthesized property and, thus, are retaining them.
-(id)init {
if (self = [super init]) {
ip = #"";
mac = #"";
vendor = #"";
icon = [[NSNumber numberWithInt:0] retain];
}
return self;
}
That should likely fix the problem (though, I'm slightly surprised, I thought 10 was still in NSNumber's instance cache. Maybe not.).
Technically you should also retain the #"" strings, but you can get away with not doing so because such strings are a special cased constant string that comes out of the compiled executable (as a private subclass of NSString that overrides to not respond to retain/release/autorelease).
The memory management guide covers this in detail. For anyone new to the platform, I would suggest re-reading it once a month (no, really -- interleaving your coding with an occasional re-read of the docs will often reveal subtle details that you didn't have enough experience to grok before. I still re-read the basic guides on a semi-annual basis.)

Zombie Messaged In For Loop

I have an ivar, keys which is an NSMutableArray containing 50 strings. When my view loads, i am getting a zombie messaged error in Instruments, and it is directing me to this line of code:
for (int row = 0; row < r; row++) {
for (int column = 0; column < c; column++){
otherArray[column][row] = [[[keys objectAtIndex:0] retain] autorelease];
//^ Instruments brings me here
[keys removeObjectAtIndex:0];
}
}
I have retained the value to keep it alive so that the remove will not cause a crash, but it still does. I have tried not retaining, and autoreleasing and it still crashes. This method of retaining and autoreleasing works when i have a local variable, but not an ivar...
I need an ivar because i need to access the strings elsewhere.
Thanks
synthesize it and release and it in your dealloc.
Solved -- Memory management problem - keys was not being correctly retained.

EXC_BAD_ACCESS Error for no conceivable reason

OK, This is a method from my program that keeps giving the EXC_BAD_ACCESS error and crashing. I indicated the line below. questionsShown is a readwrite property and points to an NSMutableArray that I initialize with a capacity of 99 at an earlier point in the program. When I debug everything appears normal in terms of the property being allocated. I assumed there must be some issue with memory management but I am having serious trouble finding the problem. Thanks in advance for any help.
#synthesize questionList;
#synthesize questionLabel;
#synthesize questionsShown;
-(IBAction)next{
int numElements = [questionList count];
int r;
if (myCount == numElements){
[questionLabel setText:#"You have seen all the questions, click next again to continue anyways."];
[questionsShown release];
questionsShown = [[NSMutableArray alloc] initWithCapacity:99];
myCount = 0;
}
else {
do {
r = rand() % numElements;
} while ([questionsShown indexOfObjectIdenticalTo:r] != NSNotFound);
NSString *myString = [questionList objectAtIndex:(NSUInteger)r];
[questionLabel setText:myString];
myCount++;
[questionsShown addObject:r]; //results in crash with message EXC_BAD_ACCESS
myCount++;
}
}
The EXC_BAD_ACCESS is coming from dereferencing r, which is just an integer. Your compiler should be giving you a warning (make pointer from integer without a cast) on that line.
If questionsShown is supposed to be some kind of index set for you (which it appears to be), you might want to either use that class, or you will have to box your integer in an NSNumber object. So:
[questionsShown addObject:[NSNumber numberWithInt:r]];
and when you read it:
[questionsShown indexOfObjectIdenticalTo:[NSNumber numberWithInt:r]]
I recommend, however, that you take a look at the NSIndexSet documentation.
With a mutable index set, you could do:
[questionsShownIndexSet containsIndex:r]
and
[questionsShownIndexSet addIndex:r]