C 为什么下面的代码是错误的?
我最近面临一个采访问题,关于以下代码的隐藏问题是什么。我无法检测到。有人能帮忙吗C 为什么下面的代码是错误的?,c,algorithm,output,C,Algorithm,Output,我最近面临一个采访问题,关于以下代码的隐藏问题是什么。我无法检测到。有人能帮忙吗 #include<stdio.h> int main(void) { char buff[10]; memset(buff,0,sizeof(buff)); gets(buff); printf("\n The buffer entered is [%s]\n",buff); return 0; } #包括 内部主(空) { 字符buff[10]; me
#include<stdio.h>
int main(void)
{
char buff[10];
memset(buff,0,sizeof(buff));
gets(buff);
printf("\n The buffer entered is [%s]\n",buff);
return 0;
}
#包括
内部主(空)
{
字符buff[10];
memset(buff,0,sizeof(buff));
获得(buff);
printf(“\n输入的缓冲区为[%s]\n”,buff);
返回0;
}
get
可以返回10个以上的字符
gets确实有问题,因为您不能告诉它只填充长度不超过10的“buff”。函数gets接受来自stdin的字符串,并且不检查缓冲区的容量。这可能会导致缓冲区溢出。这里可以使用标准功能。检查
Never use gets(). Because it is impossible to tell without knowing
the data in advance how many characters gets() will read, and because
gets() will continue to store characters past the end of the buffer,
it is extremely dangerous to use. It has been used to break computer
security. Use fgets() instead.
It is not advisable to mix calls to input functions from the stdio
library with low-level calls to read(2) for the file descriptor
associated with the input stream; the results will be undefined and
very probably not what you want.
始终建议在gets()上使用fgets()/scanf()。通过使用函数gets(),您没有将用户限制为特定文本长度的选项,这可能会导致缓冲区溢出异常。这就是为什么你不应该使用它 请尝试改用fgets(): fgets(浅黄色,最大长度)
祝你好运
memset
需要string.h
“永远不要使用gets()。因为在不事先知道数据的情况下无法判断gets()将读取多少个字符,并且因为gets()将继续存储超过缓冲区末尾的字符,所以使用它是非常危险的。它被用来破坏计算机安全。使用fgets()相反,“-获取
手册页您的代码工作……添加fflush(stdin)
和string.h
@DouglasB.stuble:否,sizeof
数组将返回数组的大小。@Billfflush()
未为输入流定义。永远不要使用fflush(stdin)
,这是一个bug,而且是未定义的行为。