scanf字段宽度字符串溢出 [英] scanf field width string overflow

查看:161
本文介绍了scanf字段宽度字符串溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which one of the following is safe regarding buffer overflow?

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

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

根据我所读的内容,我要进行第二遍(sizeof减一),但是问题非常微妙,并且我已经看到了其中的任何一个建议.有志愿者引用标准吗?

From what I've read I'm going for the second (sizeof minus one), but the matter is quite subtle and I've seen code suggesting either. Any volunteer to quote the standard?

推荐答案

C标准指出:

输入项应定义为最长的输入字节序列(不超过任何指定的最大字段宽度,可以根据字符或字节来确定,取决于转换说明符),它是匹配序列的初始子序列. /p>

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.

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

That is, the maximum field width represents how many characters there can be in the input. The extra zero value at the end is not part of the input and needs an additional space.

GNU libc手册这一点很明确:

字符串输入转换存储一个空字符来标记输入的结尾;最大字段宽度不包含此终结符.

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).

So, the only safe version is scanf("%9s", buf).

这篇关于scanf字段宽度字符串溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆