c++ - gets() 导致内存损坏?

标签 c++ c

环境: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/

相关文章:

c++ - 利用 move 语义自动隐式生成 ctors

c++ - 如何使用 C++ 在 ArmNN for Linux 中加载 base onnx 模型

c++ - 对特殊情况行为使用继承或模板

c - 该程序使用的逻辑是什么

将 <netinet/in.h> 协议(protocol)转换为名称?

c++ - 字符串归并排序

C++静态模板成员初始化问题

c - 对 sqlite_open 的 undefined reference

c - 将二维数组拆分为 C 中较小二维数组的数组

c - 在 C 中使用 scanf 解析带有 2 个不同分隔符的字符串