warning about %s in format string


James Walker
 

On 12/8/2017 3:39 PM, Jens Alfke wrote:
On Dec 8, 2017, at 9:44 AM, James Walker <list2@...> wrote:

Clang has a warning option, -Wcstring-format-directive, that produces a warning "Using %s directive in NSString which is being passed as a formatting argument to the formatting method" on a line like:

NSString* x = [NSString stringWithFormat: @"File %s", __FILE__];

Can someone please explain to me why this is something worth avoiding, or worth warning about?  I tried Googling, couldn't find anything.

Because NSString doesn’t know what text encoding the C string uses, so it just uses the process’s default encoding. This default encoding varies according to the user's locale, and also (last I checked) even if that locale is English (or most European languages) the encoding is not something useful like UTF-8 but rather the incredibly obsolete MacRoman.

The tl;dr is that if you format a non-ASCII C string with “%s” it's probably going to get mangled. In your example above, this would occur if the source file or any parent directory had a non-ASCII name.

(This is the same reason why -[NSString initWithCString:] is deprecated.)

I'll be darned, I just assumed it would use UTF-8.  Thanks.


 



On Dec 8, 2017, at 9:44 AM, James Walker <list2@...> wrote:

Clang has a warning option, -Wcstring-format-directive, that produces a warning "Using %s directive in NSString which is being passed as a formatting argument to the formatting method" on a line like:

NSString* x = [NSString stringWithFormat: @"File %s", __FILE__];

Can someone please explain to me why this is something worth avoiding, or worth warning about?  I tried Googling, couldn't find anything.

Because NSString doesn’t know what text encoding the C string uses, so it just uses the process’s default encoding. This default encoding varies according to the user's locale, and also (last I checked) even if that locale is English (or most European languages) the encoding is not something useful like UTF-8 but rather the incredibly obsolete MacRoman.

The tl;dr is that if you format a non-ASCII C string with “%s” it's probably going to get mangled. In your example above, this would occur if the source file or any parent directory had a non-ASCII name.

(This is the same reason why -[NSString initWithCString:] is deprecated.)

—Jens


James Walker
 

Clang has a warning option, -Wcstring-format-directive, that produces a warning "Using %s directive in NSString which is being passed as a formatting argument to the formatting method" on a line like:

NSString* x = [NSString stringWithFormat: @"File %s", __FILE__];

Can someone please explain to me why this is something worth avoiding, or worth warning about?  I tried Googling, couldn't find anything.