问题
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