开发者

This form of use of printf api makes it safer?

char str[] = "some text";

printf ( "%.*s", strlen(str), str );

** Of cou开发者_如何学Gorse, their buffers, strings yet to be properly targeted


No, that just shifts the problem of detecting the end of the string from printf to strlen, and it's still exactly the same.


No, printf should be safe form overruns anyway setting a field width doesn't really help


In the example you give, there's no difference. printf interprets the undecorated "%s" character code as meaning "read and print all characters from a character pointer until a null character is encountered." The initializer char str[] = "some text"; automatically appends the null character, so there will be no overrun. On the other hand, the following is not safe

char str[] = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};
printf("%s", str);

because no null character is appended to the character sequence str. On the other hand, since strlen(str) determines string length by counting the number of characters before a null is encountered, it doesn't offer you any benefit over just using printf without a field width specified.

The upshot: the only case where specifying a field width for a string is helpful is when the string isn't guaranteed to be null-terminated (or the classic case of using sprintf to write to a buffer that may not be big enough to hold the contents of str), but in that case you'd have to determine string length using something other than strlen.


No, it's no different than:

char str[] = "some text";
printf("%s", str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜