gpt4 book ai didi

c - scanf 字段宽度字符串溢出

转载 作者:太空狗 更新时间:2023-10-29 17:06:17 24 4
gpt4 key购买 nike

关于缓冲区溢出,以下哪一项是安全的?

char buf[10] = {0};
scanf("%10s", buf);

char buf[10] = {0};
scanf("%9s", buf);

从我读到的内容来看,我打算选择第二个(sizeof 减一),但问题非常微妙,我已经看到代码建议两者之一。有志愿引用标准的吗?

最佳答案

C standard指出:

An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence.

即最大字段宽度表示输入中可以有多少个字符。末尾的额外零值不是输入的一部分,需要额外的空间。

GNU libc manual明确这一点:

String input conversions store a null character to mark the end of the input; the maximum field width does not include this terminator.

因此,唯一安全的版本是 scanf("%9s", buf)

关于c - scanf 字段宽度字符串溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24746111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com