printf api 的这种使用形式使其更安全?
char str[] = "some text"; printf ( "%.*s", strlen(str), str );
** 当然,它们的缓冲区、字符串还没有被正确定位
char str[] = "some text"; printf ( "%.*s", strlen(str), str );
** Of course, their buffers, strings yet to be properly targeted
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这只是将检测字符串结尾的问题从 printf 转移到了 strlen,而且仍然完全相同。
No, that just shifts the problem of detecting the end of the string from printf to strlen, and it's still exactly the same.
不, printf 应该是安全的形式溢出,无论如何设置字段宽度并没有真正的帮助
No, printf should be safe form overruns anyway setting a field width doesn't really help
在你给出的例子中,没有区别。 printf 将未修饰的“%s”字符代码解释为“从字符指针读取并打印所有字符,直到遇到空字符”。初始化器
char str[] = "some text";
自动附加空字符,因此不会出现溢出。另一方面,以下内容并不安全,因为没有将空字符附加到字符序列
str
中。另一方面,由于strlen(str)
通过计算遇到 null 之前的字符数来确定字符串长度,因此与仅使用printf
相比,它不会给您带来任何好处> 未指定字段宽度。结果:为字符串指定字段宽度有帮助的唯一情况是当字符串不能保证以 null 终止时(或者使用 sprintf 写入缓冲区的经典情况可能不够大,无法容纳
str
的内容),但在这种情况下,您必须使用strlen
以外的其他方法来确定字符串长度。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 safebecause no null character is appended to the character sequence
str
. On the other hand, sincestrlen(str)
determines string length by counting the number of characters before a null is encountered, it doesn't offer you any benefit over just usingprintf
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 ofstr
), but in that case you'd have to determine string length using something other thanstrlen
.不,这与以下内容没有什么不同:
No, it's no different than: