NSString 分配错误?
我使用了下面的代码:
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];
}
但我收到此错误 3 次,为什么?
错误:
myapp(15467,0xacdaa2c0) malloc: *** error for object 0x4eb1ca0: pointer being freed was not allocated
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
删除
try
and remove
在循环内的第一个字符串中,您声明指针
theString
并分配一个对象:在第二行中,您将指针
theString
重定向到新分配的自动释放字符串[ theString stringByAppendingFormat:@"%i.jpg",i];
,所以之前分配的对象就丢失了。这是内存泄漏。最后,释放自动释放的字符串
[theString release];
,这将释放该对象,并在自动释放循环尝试再次释放该对象时使应用程序崩溃。解决方案:阅读 edsko 的答案。
In the first string inside the loop you declare the pointer
theString
and allocate an object: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.
stringByAppendingFormat 返回一个新字符串,并自动释放。因此,这意味着您正在释放一个自动释放的对象,这就是您收到错误的原因,并且您泄漏了第一行分配的字符串。我建议将第一行更改为
然后完全删除该版本。
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
and then delete the release completely.