Gets()导致内存损坏

gets() causes memory corrupt?

本文关键字:内存 损坏 Gets      更新时间:2023-10-16

环境: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没有,因此容易发生缓冲区溢出。