问题描述
我的snprintf
键,可避免缓冲区溢出,但为什么没有被调用的函数 snscanf
code:
INT的main()
{
字符* SRC =helloeveryone;
炭BUF1 [5];
sscanf的(SRC,%S,确定buf1); //这里是一个数组越界}
所以,我觉得还需要 snscanf
。为什么我们只有的snprintf
?
有争议的(和可选的)附件K到C11增加了一个 sscanf_s
函数,该函数的附加参数 rsize_t
(在附件K定义)后,指针参数类型,指定所指向的数组的大小。是好还是坏,这些功能都没有得到广泛的支持。可以通过将在转换指定的尺寸,例如达到相同的结果。
烧焦了[20];
sscanf的(在%19秒,淘汰);
但是这是尴尬的,而且容易出错,如果目标对象可能会在运行时有所不同的大小(你将不得不与的snprintf
编程构造转换说明)。请注意,在转换说明字段宽度是读取的最大输入字符数,的sscanf
也为%S 的转换,所以你通过字段宽度必须严格比目标对象的大小更小。
I have snprintf
and it can avoid a buffer overflow, but why there is no function called snscanf
?
Code:
int main()
{
char * src = "helloeveryone";
char buf1[5];
sscanf(src,"%s",buf1); // here is a array out of bounds
}
So, I think a snscanf
is also needed. Why do we have only have snprintf
?
The controversial (and optional) Annex K to C11 adds a sscanf_s
function which takes an additional argument of type rsize_t
(also defined in Annex K) after the pointer argument, specifying the size of the pointed-to array. For better or worse, these functions are not widely supported. You can achieve the same results by putting the size in the conversion specifier, e.g.
char out[20];
sscanf(in, "%19s", out);
but this is awkward and error-prone if the size of the destination object may vary at runtime (you would have to construct the conversion specifier programmatically with snprintf
). Note that the field width in the conversion specifier is the maximum number of input characters to read, and sscanf
also writes a terminating null byte for %s
conversions, so the field width you pass must be strictly less than the size of the destination object.
这篇关于由于我们的snprintf,为什么我们没有snscanf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!