Re: Memory management question
Re: Memory management question
- Subject: Re: Memory management question
- From: Andy Lee <email@hidden>
- Date: Mon, 29 Apr 2002 13:14:49 -0400
At 6:49 PM +0200 4/29/02, Philippe Martin wrote:
-( void )doSomeThing {
int i;
NSArray *myArray;
for ( i = 0; i < [ anotherArray count ]; i++ ) {
myArray = [ [ NSArray alloc ] init ];
myArray = [ [ anotherArray objectAtIndex:i ]
componentsSeparatedByString:@"\t" ];
// do something here
[ myArray release ];
myArray = nil;
}
}
}
This crashed my application with an "EXC_BAD_ACCESS" signal.
You were setting the variable myArray twice. The second time...
myArray = [ [ anotherArray objectAtIndex:i ]
componentsSeparatedByString:@"\t" ];
...you were assigning an autoreleased object to myArray (because
-componentsSeparatedByString: returns an autoreleased object). Your
release statement was actually releasing that object, causing it to
be released one too many times, hence the crash.
Also, there was a memory leak. The first array object you created with...
myArray = [ [ NSArray alloc ] init ];
...would never get released, because you immediately changed myArray
to something else, thereby losing the program's only reference to
that instance.
I fixed it by making myArray "autoreleased", with something like this:
-( void )doSomeThing {
int i;
for ( i = 0; i < [ anotherArray count ]; i++ ) {
NSArray *myArray = [ [ anotherArray objectAtIndex:i ]
componentsSeparatedByString:@"\t" ];
// do something here
}
}
}
This is probably the code you should have had in the first place. It
looks like you didn't really need to create a new, empty array
instance, which is what "[ [ NSArray alloc ] init ]" does.
--Andy
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.