Reputation: 5426
i used the code below :
for (int i=1; i<=3;i++){
NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue];
theString = [theString stringByAppendingFormat:@"%i.jpg",i];
[img addObject:theString];
NSLog(@"the string %@:",theString); //01.jpg ,02.jpg and 03.jpg
[theString release];
}
but i got this error 3 times why ?
Error:
myapp(15467,0xacdaa2c0) malloc: *** error for object 0x4eb1ca0: pointer being freed was not allocated
Upvotes: 0
Views: 231
Reputation: 4623
In the first string inside the loop you declare the pointer theString
and allocate an object:
NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue];
In the second line you redirect the pointer theString
to the new allocated autoreleased string [theString stringByAppendingFormat:@"%i.jpg",i];
, so the previously allocated object is lost. This is a memory leak.
Finally, you release the autoreleased sting [theString release];
, which will deallocate the object and crash the application when the autorelease loop will try to release the object again.
Solotion: read the edsko's answer.
Upvotes: 1
Reputation: 10864
try
NSString *theString = [[NSString alloc] initWithFormat:@"%i%i.jpg",imageValue,i];
and remove
theString = [theString stringByAppendingFormat:@"%i.jpg",i];
Upvotes: 1
Reputation: 1628
stringByAppendingFormat returns a new string, with is autoreleased. So that means you are releasing an autoreleased object, which is why you're getting the error, and you're leaking the string allocated on the first line. I would suggest to change that first line to
NSString* theString = [NSString stringWithFormat:@"%i", imageValue];
and then delete the release completely.
Upvotes: 1