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);
}
该程序在执行时将崩溃。这是文本文件的两个链接。
alphaLow3.txt
alphaLow2.txt
要运行alphaLow2.txt,请将
load_file
调用中的数字分别更改为676
和2
。该程序读取alphaLow2.txt时,将成功执行。但是,当它读取alphaLow3.txt时,它崩溃了。该文件只有172KB。我的文件大小为MB或更大。我以为我分配了足够的内存,但是我可能丢失了一些东西。
该程序应该在
C
中,但是为了方便起见,我包含了一些C++
函数。任何建设性的意见表示赞赏。
最佳答案
您必须确认文件长度。在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';
关于c++ - 读取长文本文件时程序崩溃-“* .exe停止工作”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20459949/