NSString overflows its buffer and app crashed. Debugger doesn't see any stack trace information. But why?

戏子无情 提交于 2019-12-11 07:39:18

问题


I spent a lot of time to find out why my app crashed. My count variable doesn't properly initialized in some cases.

NSString overflows its buffer and app crashed. Debugger doesn't see any stack trace information. But why?

int count = 2147483647;
NSString *lines = @"";
for(int i = 0; i < count; i ++)
{
    lines = [NSString stringWithFormat:@"%@%@", lines, @"\n"];
}

UPDATE: Why doesn't debugger show any stack trace information?


回答1:


You're not only creating long strings, you're creating lots of strings. Every call to +stringWithFormat: creates a new string that's one character ('\n') longer than the one before. Those strings are autoreleased but the autorelease pool never gets drained, so you're filling up memory with a great many strings like @"\n", @"\n\n", @"\n\n\n", @"\n\n\n\n", and so on. You're probably crashing from that long before you reach any internal buffer size limit (if there is one) in NSString.




回答2:


Use this to find out how far you get:

int count = 2147483647;
NSString *lines = @"";
for (int i = 0; i < count; i++) {
    @try { 
        lines = [lines stringByAppendingString:@"\n"];
    }
    @catch (NSException *ex) {
        NSLog(@"end after %d loops (%@)", i, [ex description]);
    }
}


来源:https://stackoverflow.com/questions/9906438/nsstring-overflows-its-buffer-and-app-crashed-debugger-doesnt-see-any-stack-tr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!