gnustep-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSString bug with test and really dodgy patch.


From: Richard Frith-Macdonald
Subject: Re: NSString bug with test and really dodgy patch.
Date: Tue, 2 Oct 2012 22:40:49 +0100

On 2 Oct 2012, at 22:10, Chris Ball wrote:

> 
> I ran into some problems the other day with clang's address sanitizer getting
> very cross with me and I eventually chased it down to [NSString 
> initWithFormat:
> arguments:]  specifically GSFormat.m blithely calls strlen on my input string
> even if I have specified a precision, this is not good given that I'm not
> dealing with null terminated strings for the most part.  I expect the same bug
> affects stringWithFormat and probably other stuff as well but I haven't 
> bothered
> to look into what all uses the GSFormat stuff too closely.

I kind of agree with your sentiments (having been bitten by that myself when 
logging stuff), but I investigated it at the time and GSFormat.m is right and 
your code is wrong.

The reason is that the %s format deal with a nul terminated c-string argument, 
and by definition that's *not* an array of char whose length is determined by 
the precision of the format string, the nul terminator is *mandatory*.  If you 
code passes an argument which is not nul terminated than your code is doing 
something illegal and you can't really complain about *anything* that happens.
Also, the precision in the format works in conjunction with field width and 
alignment ... the format code needs to determine the length of the string you 
passed (using strlen) when it decides which part of the string to use ... so in 
the case where the rightmost part of the string should be displayed, using the 
precision as the length would give the wrong result.

We could probably adapt your patch to use precision as string lengh in those 
cases where it will work, but you can't catch all cases that way ... so maybe 
it's better if people find out as soon as possible that c-strings have to be 
nul terminated.

Sorry about this ... but it's a behavior inherited from the C stdio library and 
posix etc standards.  My own feeling is that format strings *ought* to provide 
some way of working with unterminated strings, but they just don't, so you have 
to copy the data into a big enough buffer, add the nul terminator, and use that 
buffer intead of the original data :-(


reply via email to

[Prev in Thread] Current Thread [Next in Thread]