![](/img/trans.png)
[英]How to fix and understand this Segmentation Fault (core dump) error? I cannot comprehend it whatsoever
[英]I cannot understand core dump cause of fgetc, how can I fix it?
我这样分配矩阵:
prevMatrix = (int**)malloc(sizeof(int) * arraySize[0]);
for (int i = 0; i < arraySize[0]; i++) {
prevMatrix[i] = (int*)malloc(sizeof(int) * arraySize[1]);
}
我检查了arraySize[]
具有正常值。 arraySize[0]
表示行, arraySize[1]
表示列。
我像这样交出矩阵:
void getInputMatrix(FILE* input, int column, int** matrix)
getInputMatrix(input, arraySize[1], prevMatrix);
然后函数的主体是这样的:
void getInputMatrix(FILE* input, int column, int** matrix) {
int i = 0, j = 0, c = 0;
while (!feof(input)) {
if (j == column) {
j = 0;
i++;
}
c = fgetc(input);
if (c != EOF && c != 32 && c != 10 && c != 13) {
matrix[i][j] = c - 48;
j++;
}
}
}
这是矩阵文件的示例:
1 0 0 0 0 0 0
0 1 0 1 0 0 0
0 1 0 0 1 1 0
0 1 1 1 0 0 0
0 0 0 0 1 0 0
0 1 0 0 0 1 0
1 0 1 1 0 0 0
0 1 0 0 0 0 1
它在 VS 2019 中运行良好,但在 Linux 系统(Ubuntu)中导致分段错误。
该程序在 Linux 中运行良好,直到列为 6 或 7,但是当列超过该数字时,它会发生corrupted size vs. prev_size
错误或segmentation fault
。
是分配的问题吗? 还是 fgetc()? 我该如何解决?
对于初学者,您的第一级分配应该使用int
指针的大小而不是int
:
int **prevMatrix = malloc(sizeof(int*) * arraySize[0]);
如果这些类型的大小不同,则您的原始代码可能有问题。
而且,顺便说一句,您不应该在 C 中转换malloc
返回值,这可能会导致细微的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.