printf api 的这种使用形式使其更安全?

发布于 2024-08-12 17:34:05 字数 108 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

流殇 2024-08-19 17:34:05

不,这只是将检测字符串结尾的问题从 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.

很酷不放纵 2024-08-19 17:34:05

不, printf 应该是安全的形式溢出,无论如何设置字段宽度并没有真正的帮助

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

谢绝鈎搭 2024-08-19 17:34:05

在你给出的例子中,没有区别。 printf 将未修饰的“%s”字符代码解释为“从字符指针读取并打印所有字符,直到遇到空字符”。初始化器 char str[] = "some text"; 自动附加空字符,因此不会出现溢出。另一方面,以下内容并不安全,

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

因为没有将空字符附加到字符序列 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 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.

凉栀 2024-08-19 17:34:05

不,这与以下内容没有什么不同:

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

No, it's no different than:

char str[] = "some text";
printf("%s", str);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文