Gets()导致内存损坏
gets() causes memory corrupt?
环境: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 failedn");
return -1;
}
gets(strbuf1);
TestNum = atoi(strbuf1);
for (k = 0; k < TestNum; k++){
gets(strbuf1);
printf("k= %d, strbuf1=%sn", k, strbuf1);
//--- read data ---//
idx = 0;
while (idx < 5){
gets(strbuf1);
idx ++;
}
}
return 0;
}
将代码构建成可执行文件(例如foo.exe)后,我使用"foo.exe <Testinput.txt"在CMD窗口下。它一路上都会坏,但我不知道为什么。有人知道吗?>
我已经上传了"testinput.txt"文件到GDrive, https://docs.google.com/document/d/1d8jBPZfYYjtA9R1CldUZhyRvaAiK5Xk9K-mhE6dIDKU/edit?usp=sharing
替换这一行:
gets(strbuf1);
:
fgets(strbuf1, 10000, stdin);
这是因为fgets
有缓冲区大小参数以避免溢出,而gets
没有,因此容易发生缓冲区溢出。
相关文章:
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 正在调试 malloc():新内存损坏
- 仅特定内核计数上的 MPI 内存损坏
- C++程序错误:malloc():内存损坏
- 调用std::函数成员时内存损坏
- C++ 内存损坏检测
- 由于标头中的 #define 不匹配而导致内存损坏
- C STD ::线程中的种族状况或内存损坏
- malloc()内存损坏仅通过为特定数量编写int数组
- 字符串标记化期间的内存损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- std :: string ::擦除会导致内存损坏
- 编译器如何检测内存损坏
- mix_playMusic导致内存损坏
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- 两个内联程序集调用与一个内联程序集调用中的内存损坏?
- 如何调试不确定内存损坏?
- 增强Dijkstra代码会导致片段内存损坏
- 内存损坏从vb.net调用c dll