scanf不超过缓冲区溢出 [英] scanf not to exceed buffer overrun
问题描述
我有一个缓冲区,我不希望用户输入的字符超出缓冲区可以容纳的字符数(以避免缓冲区溢出)。
I have a buffer and I don't want the user to enter more characters than the buffer can hold (to avoid a buffer overrun).
我正在使用 scanf
并执行以下操作:
I am using scanf
and have done like this:
char buffer[30] = {'\0'};
scanf("%30s", buffer);
但是,如果用户输入的字符数超过30,我知道我会受到保护。但是,如果用户输入超过30,缓冲区将以null终止吗?
However, I know I am protected if the user enters more than 30. However, if the user enters more than 30, will the buffer be null terminated?
推荐答案
scanf()
带有%s转换说明符的缓冲区会添加一个终止的空字符。
scanf()
with a "%s" conversion specifier adds a terminating null character to the buffer.
但是,您要输入30个字符,实际上表示31,只能容纳30个空间。您应该使用最大字段宽度为29。
But, you're asking for 30 characters, which really means 31 and only have space for 30. You should use a maximum field width of 29.
char buffer[30] = {'\0'};
scanf("%29s", buffer);
还要注意,转换说明符%c
的工作原理与%s
相似,但是不会添加终止的空字符,也不会从输入中丢弃空格。取决于您的期望,它可能比使用%s更好。
Also note that the conversion specifier "%c"
works pretty much like "%s"
, but does not add the terminating null character and does not discard space from the input. Depending on what you expect, it might be better than using "%s".
char buffer[30] = {'\0'};
scanf("%29c", buffer);
buffer[29] = '\0';
这篇关于scanf不超过缓冲区溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!