strcat+strcat+strcat == baaad

Shachar Shemesh wine-devel at sun.consumer.org.il
Sun Dec 1 14:15:05 CST 2002


Alexandre Julliard wrote:

>Shachar Shemesh <wine-devel at sun.consumer.org.il> writes:
>
>  
>
>>Well - still snprintf is more efficient.
>>    
>>
>
>I don't think so, but feel free to provide benchmarks.
>  
>
Benchmark will follow soon. In the mean time, think about the fact that, 
compared to linear copying of the strings in, these are the overheads 
(neglecting function call overhead, which is not neglectible but is fair):
n - number of strings in the final string
m(i) - length of string i (0<i<=n)
sm(i) - sigma of all lengths up to i (0<i<=n)
sm(n) - total length of all strings
with sprintf - parsing the format string*n+sm(n)
with strcpy+strcat - for each strcat we have to find the end of the 
string (sm(i-1)), and then write our own string (m(i)).

>>But there is also no reason not to welcome these submissions if
>>someone already took the time to submit them.
>>    
>>
>
>There's no objective reason why sprintf is better than strcat in that
>case, it's purely a matter of personal taste.
>
Not if you accept my performance claim. Also, there is the security 
thingamy.

The str* method is a bitch to make secure. You have to keep subtracting 
the already processed strings from the remaining buffer length, and then 
you run into the risk of subtracting more than you have, resulting in a 
negative number=buffer overflow despite your best efforts. There is the 
question of the null - yes/no. There is a horrible performance hit for 
strncpy for filling the entire buffer, while not promising null 
termination. In short, it is one major headache.

snprintf, on the other hand, is simple, to the point, and clean. You 
still have to make sure the buffer is terminated, but that's all.

> As such, whoever writes
>the code in the first place gets to choose the way it's done.
>
Agreed, assuming ALLof my previous arguments are rejected.

> What if
>I apply that patch and someone sends a patch tomorrow changing the
>sprintfs back into strcats because he prefers that?  Should I apply
>it?  After all he took the time to submit it too...
>  
>
I said that due to the wall to wall agreement over the superiority of 
sprintf/snprintf. If there is a consensus, we should stick to it.

                Shachar







More information about the wine-devel mailing list