【发布时间】:2020-12-29 22:46:46
【问题描述】:
使用 gcc 进行编译时,我收到错误消息“分段错误(核心转储)”,但我找不到访问超出限制内存的点。我什至试图只部分填充矩阵,但在我成功地从文件中读取所有值之后,我得到了相同的错误消息。读取最后一个元素后触发错误
#include <stdio.h>
#include <stdlib.h>
#define NR 4
#define NC 8
#define FILENAME "../debug.log"
int ndominanti(int [][NC], int);
int main(int argc, char * argv[]){
int info[NR][NC];
FILE * pf;
int i, j, ris;
if(pf = fopen(FILENAME, "r")){
for(i = 0; i < NR; i++)
for(j = 0; j < NC; j++)
fscanf(pf, "%d", &info[i][j]);
/* this is where the error occurs */
fclose(pf);
ris = ndominanti(info, NR);
printf("ris: %d\n", ris);
}else
printf("Errore apertura file %s\n", FILENAME);
return 0;
}
int ndominanti(int info[][NC], int nrighe){
int i, j, k, h;
int curr, ndom, nrighedim, ncoldim;
int isdom;
nrighedim = nrighe - 1;
ncoldim = NC - 1;
ndom = 0;
for(i = 0; i < nrighedim; i++)
for(j = 0; i < ncoldim; j++){
curr = info[i][j];
isdom = 1;
for(k = i + 1; k < nrighe && isdom; k++)
for(h = j + 1; h < NC && isdom; h++)
if(curr <= info[k][h])
isdom = 0;
if(isdom)
ndom++;
}
return ndom;
}
这是 debug.log 文件的内容,每行由 CRLF 分隔,单个元素由单个空格分隔,最后有一个 CRLF
5 9 2 4 1 7 2 4
3 5 6 2 5 6 1 2
1 3 4 7 8 8 3 0
1 3 5 6 7 8 2 1
【问题讨论】:
-
编译时出现分段错误?
-
你的意思是“for(j = 0; j
-
for(j = 0; i < ncoldim; j++)->for(j = 0; j < ncoldim; j++) -
提示:使用调试器。似乎您实际上并不知道触发段错误的确切行。调试器可以立即为您提供该信息,也可以用于检查变量。
-
@Peter-ReinstateMonica - 这个评论应该是个玩笑吗?有一条用另一种语言输出的消息。
标签: c matrix segmentation-fault text-files