【发布时间】:2017-11-19 10:57:17
【问题描述】:
我正在尝试读取文件并存储其中包含的内容,但出现分段错误,这是我的代码的一部分:
int nnodes;
int main(){
FILE * file = fopen("pub08.in", "r");
int nkeys;
fscanf(file, "%d %d", &nnodes, &nkeys);
long int graphsize = nnodes * nnodes;
long int * graph = malloc(graphsize * sizeof (long int));
for (int i = 0; i < graphsize; i++) {
graph[i] = IN;
}
for (int i = 0; i < nnodes; i++) {
long int a, b, prize;
fscanf(file, "%ld %ld %ld", &a, &b, &prize);
graph[a * nnodes + b] = prize;
graph[b * nnodes + a] = prize;
}
}
文件 pub08.in 如下所示:
100000 10000
61268 56095 10
40567 20917 17
97937 47973 13
74088 21826 13
62183 30464 11
97793 80708 12
35121 90180 10
77067 97297 17
4657 33995 16
88147 42709 18
95937 25936 19
79853 24452 11
9677 36288 11
91869 48767 15
34585 46478 17
41874 40622 15
13700 19942 18
15660 79277 14
...
分段错误发生在网上:
graph[a * nnodes + b] = prize;
我做错了什么?
【问题讨论】:
-
您请求大约 4 或 8 GB 的内存(取决于您的
sizeof(long int))。你确定你有那么多吗? -
哦,对,没错。我其实没有。我只有 1 GB
标签: c segmentation-fault malloc large-files