我用C语言写了一个程序当我试图用我的小txt文件作为参数运行它时,我没有问题不幸的是,当我试图加载更大的文件时,我遇到了分段错误(核心转储)甚至我的主函数的一行也没有执行这是启动和加载txt文件作为我的argv[1]参数的部分代码,我不知道问题出在哪里,大的txt文件大约是13MB我在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个字节,那么要放在堆栈上的数据就超过了12MB。
在大多数linux系统上,堆栈上需要的数据量超过了usal默认的堆栈大小(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.file加载到C程序时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29061513/