环境:VS2013 express,Windows 7。
源代码非常简单:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int TestNum, k, idx;
char *strbuf1 = NULL;
strbuf1 = (char *)malloc(sizeof(char) * 10001);
if (strbuf1 == NULL){
printf("memory allocation failed\n");
return -1;
}
gets(strbuf1);
TestNum = atoi(strbuf1);
for (k = 0; k < TestNum; k++){
gets(strbuf1);
printf("k= %d, strbuf1=%s\n", k, strbuf1);
//--- read data ---//
idx = 0;
while (idx < 5){
gets(strbuf1);
idx ++;
}
}
return 0;
}
将代码构建成可执行文件后,比如 foo.exe,我在 cmd 窗口下用“foo.exe < testinput.txt”对其进行了测试。一路上会坏掉,但我也说不出为什么。有人知道吗?
我已将“testinput.txt”文件上传到 GDrive,https://docs.google.com/document/d/1d8jBPZfYYjtA9R1CldUZhyRvaAiK5Xk9K-mhE6dIDKU/edit?usp=sharing
最佳答案
替换这一行:
gets(strbuf1);
与:
fgets(strbuf1, 10000, stdin);
这是因为fgets
有缓冲区大小的参数来避免溢出,而gets
没有,因此容易出现缓冲区溢出。
关于c++ - gets() 导致内存损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443217/