I am doing a program which reads 3x3 matrices.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row;
int col;
long **tab;
} matr;
int SIZE = 3;
void *emalloc(size_t size) {
void *memory = malloc(size);
if (!memory) {
fprintf(stderr, "ERROR: Failed to malloc.\n");
exit(1);
}
return memory;
}
void file_to_matrix(FILE *path_matr, matr *m) {
long **matrix = (long**) emalloc(SIZE * sizeof(long*));
for (int i = 0; i < SIZE; i++) matrix[i] = (long*) emalloc(SIZE * sizeof(long));
char line[4];
fscanf(path_matr, " %[^\n]", line);
// This code does not give SEGFAULT
// for (int i = 0; i < SIZE; i++) {
// fscanf(path_matr, "%ld%ld%ld", &matrix[i][0], &matrix[i][1], &matrix[i][2]);
// }
// The code below gives SEGFAULT
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
fscanf(path_matr, "%ld", &matrix[i][j]);
}
}
m->row = SIZE;
m->col = SIZE;
m->tab = matrix;
}
int main(int args, char *argv[]) {
FILE *path_matr = fopen(argv[1], "r");
/*Getting the matrices*/
int n_matr; // Number of matrices
fscanf(path_matr, "%d", &n_matr);
matr *matrices = emalloc(n_matr * sizeof(matr));
for (int i = 0; i < n_matr; i++) {
file_to_matrix(path_matr, &matrices[i]);
}
for (int i = 0; i < n_matr; i++)
free(matrices[i].tab);
free(matrices);
fclose(path_matr);
return 0;
}
Notice there are two for-loops in file_to_matrix function. One version gives segmentation fault, the other does not. Why? Funny thing is: if I enable -O2, both version works.
Compiled with gcc -std=c11 test.c -o test -g && ./test in.txt (gcc version 4.9.2).
in.txt:
3
∗∗∗
11 12 1444
21 22 23
31 32 33
∗∗∗
11 12 13
21 22 23
31 32 33
∗∗∗
11 12 13
21 22 23
31 31 33
∗∗∗
P.S.: The code I posted here is part of another code, from which I removed some blocks (such as checking the number of arguments, fopen's return, etc) for simplicity. The issues I describe here also happens with the original code.
path_matr
or returning a value frommain()
).