NSString stringWithFormat: crash

Can someone shed some light on this misterious crash? I have some very trivial code which causes the following crash on `_CFStringCreateWithFormatAndArgumentsAux2`. Any ideas how to investigate this further? My only assumption is corrupted memory that manifests like that.

Code

  NSString *formatedString = nil;
  NSInteger seconds = x;
  NSInteger hours = y;
  NSInteger minutes = z;
  if (hours > 0) {
    return [NSString stringWithFormat:@"%zd:%02zd:%02zd", hours, minutes, seconds];
  } else {
    return [NSString stringWithFormat:@"%zd:%02zd", minutes, seconds];
  }

Stacktrace

0 libsystem_malloc.dylib 0x1994f3be8 szone_free + 2944
1 libsystem_malloc.dylib 0x1994f3734 szone_free + 1740
2 CoreFoundation 0x183f590e0 CFRelease + 1084
3 CoreFoundation 0x184041980 _CFStringCreateWithFormatAndArgumentsAux2 + 264
4 Foundation 0x184ec5e0c -[NSPlaceholderString initWithFormat:locale:arguments:] + 164
5 Foundation 0x184ec5cdc +[NSString stringWithFormat:] + 64

I put your code into a simple test project and it doesn’t crash for me. I suspect that you have a memory management problem elsewhere in your program that’s being triggered here. Try running with Zombies to see if that helps reveal the issue. If that doesn’t work, try Address Sanitizer.

ps It looks like you’re formatting time intervals, and there’s a much better way to do that, namely

NSDateComponentsFormatter
. However, don’t make that change until you’ve got to the bottom of your crashing bug. Such a change might mask the bug, only to have it show up later on in much harder-to-debug circumstances (like when your app is deployed to end users).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Have you checked what are x, y, z on call ?


There was a long discussion in this forum a few months ago on this issue:

h ttps://forums.developer.apple.com/thread/66518

NSString stringWithFormat: crash
 
 
Q