Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get the warning "Format not a string literal and no format arguments" at NSLog -- how can I correct this in the code supplied?

Tags:

cocoa

I get the warning "Format not a string literal and no format arguments" on the NSLog call in the following block:

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog([NSString stringWithFormat:@"%d", buttonIndex]);
}

I have read in another post here that this error message indicates an insecure use of NSLog. Could someone point me in the direction of a properly formatted string for this?

like image 722
Sosullivan Avatar asked May 31 '10 23:05

Sosullivan


1 Answers

It's technically an invalid warning in your case, but it's telling you that your format string for NSLog is not hard-coded and could could be a security/stability issue. The fix is simple:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%d", buttonIndex);
}

In case you're curious, what I mean by security/stability issue is this. In my example, the format string for NSLog is constant: @"%d", and you know when you compile it that NSLog will expect a single integer to be passed. When you call NSLog like NSLog([obj makeSomeString]), you don't really know at compile time what the format string is, or how many/which types of arguments should follow. If at run-time the string turns out to be "%d %d %@", it will happily read two integers and an NSObject from the stack, regardless of whether any objects were actually put there. That's the problem it's warning you of.

The warning is invalid in your case because the string you're generating has a format of %d, so it should never include the % character that would cause this problem to manifest.

like image 195
alltom Avatar answered Sep 29 '22 06:09

alltom