我用C语言写了一个程序。当尝试使用我的小 txt 文件作为参数运行它时,我没有任何问题。不幸的是,当我尝试加载更大的文件时,我遇到了段错误(核心转储。甚至我的主函数的 1 行也没有执行。这是负责启动和加载 txt 文件作为我的 argv[1] 参数的代码的一部分.我真的不明白问题出在哪里。大 Txt 文件大约有 13 MB。我正在 linux(ubuntu) 上工作。如果您能提供帮助,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
int wage;
}Edge;
int main(int argc, char *argv[]) {
printf("Program starts");
int x,y,z;
int counter = 1;
int N,E; //node,edges
FILE *fid;
fid = fopen(argv[1],"r");
fscanf(fid,"%d%d",&N,&E);
Edge Graph[E];
int visited[N+1];
while(counter <= E){
fscanf(fid, "%d%d%d", &x, &y,&z);
Graph[counter-1].x=x;
Graph[counter-1].y=y;
Graph[counter-1].wage=z;
counter=counter+1;
}
printf("\nWe load all edges. Here is our Graph");
fclose(fid) ;
printf("Program ends");
return 0;
}
最佳答案
首先是一些近似值:
对于 13MB 的数据,您的文本文件肯定包含超过 100 万条边(假设节点 x 和 y 分别用 3 位数字后跟一个空格平均表示,工资平均用 1 位数字后跟一个空格表示) )和至少 1400 个节点。
你的可变长度数组Graph[E]和visited[N+1]是局部变量,因此存储在堆栈中。假设每个整数有 4 个字节,则需要放入堆栈的数据超过 12 MB。
您需要的堆栈数据量超出了大多数 Linux 系统上通常的默认堆栈大小 (8 MB)。
您可以考虑增加堆栈大小,如 this SO question 中所述。 。
但是你真的应该更好地考虑动态分配:
Edge *Graph = calloc (sizeof(Edge),E);
int *visited = calloc (sizeof(int), N+1);
if (Graph==NULL || visited==NULL) {
printf ("Oops ! Out of memory (%d edges, %d notes) !!", E, N+1);
exit (1); // or some other kind of error handling
}
关于c - 将大 txt. 文件加载到 C 程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29061513/