读取长文本文件时程序崩溃 - " * .exe已停止工作"

时间:2013-12-08 22:24:12

标签: c++ c memory-management file-io

RR标题描述了一切。我正在我的程序中读取各种文件,一旦它到达一个相对较大的文件,程序崩溃。

我写了一个缩短版本的程序来复制这个问题。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <fstream>

char** load_File(char** preComputed, const int lines, const int sLength,
                 std::string fileName){
    //Declarations
    FILE *file;
    int C = lines+1;
    int R = sLength+2;
    int i; //Dummy index
    int len;

    //Create 2-D array on the heap
    preComputed = (char**) malloc(C*sizeof(char*));

    for(i = 0; i<C; i++) preComputed[i] = (char *) malloc(R*sizeof(char));
    //Need to free each element individually later on

    //Create temprary char array
    char* line = (char *) malloc(R*sizeof(char));
    assert(preComputed);

    //Open file to read and store values
    file = fopen(fileName.c_str(), "r");
    if(file == NULL){ perror("\nError opening file"); return NULL;}
    else{
        i = 0;
        while(fgets(line, R, file) != NULL){
            //Remove next line
            len = R;
            if((line[len-1]) == '\n') (line[len-1]) = '\0';
            len--; // Decrement length by one because of replacing EOL
                   // with null terminator     

            //Copy character set
            strcpy(preComputed[i], line);
            i++;
        }
        preComputed[C-1] = NULL; //Append null terminator
        free(line);
    }
    return preComputed;
}

int main(void){
    char** preComputed = NULL;
    std::string name = "alphaLow3.txt";

    system("pause");

    preComputed = load_File(preComputed, 17576, 3, name);
    if(preComputed == NULL){
        std::cout<<"\nAn error has been encountered...";
        system("PAUSE");
        exit(1);
    }
    //Free preComputed
    for(int y = 0; y < 17576; y++){
        free(preComputed[y]);
    }
    free(preComputed);
}

该程序执行时会崩溃。以下是文本文件的两个链接。

  1. alphaLow3.txt
  2. alphaLow2.txt
  3. 要运行alphaLow2.txt,请分别将load_file来电中的号码更改为6762

    当该程序读取alphaLow2.txt时,它会成功执行。但是,当它读取alphaLow3.txt时,它会崩溃。这个文件只有172KB。我有MB或更大的文件。我以为我分配了足够的内存,但我可能会遗漏一些东西。

    该程序应该在C中,但我已经包含了一些C++功能以便于使用。

    赞赏任何有建设性的意见。

1 个答案:

答案 0 :(得分:1)

你必须确认你的文件长度。在alphaLow3.txt文件中,共有35152行。但是在你的程序中,你设置了17576行。这是导致崩溃的主要原因。

另外,这句话

if((line[len-1]) == '\n') (line[len-1]) = '\0';

fgets会使最后一个字符为NULL。例如,第一行应该是“'a''a''a''\ n''null'”。所以你应该这样做。

if((line[len-2]) == '\n') (line[len-2]) = '\0';