Advertisements
I’m working on a GDB project for class an I’m finding issues with a segfault portion in a piece of code that reads a file and creates a matrix with the input. GDB brings me to the "printf("%.2d\t", mat[row][col]);" in printMatrix() but I can’t seem to grasp what exactly goes wrong.
int main(int argc, char* argv[])
{
FILE* fp = fopen(argv[1], "r");
int size = 0;
int **mat = readFile(fp, &size);
printMatrix(mat, size);
return 0;
}
int** readFile(FILE* fp, int *size)
{
fscanf(fp, "%d", size);
int num = *size;
int index = 0;
int** mat = (int**)malloc(num * sizeof(int));
for(index = 0; index < num; index++)
mat[index] = (int*)malloc(num * sizeof(int));
int row = 0;
int col = 0;
for(; row < num; row++)
{
for(; col < num; col++)
{
fscanf(fp, "%d", &mat[row][col]);
}
}
return mat;
}
void printMatrix (int** mat, int num)
{
int row = 0;
int col = 0;
for(row = 0; row < num; row++)
{
for(col = 0; col < num; col++)
{
printf("%.2d\t", mat[row][col]); /* gdb indicates segfault here */
}
printf("\n");
}
}
I tried tinkering with the for loop but can’t seem to get the expected output.
>Solution :
int** mat = (int**)malloc(num * sizeof(int));
It should be
int** mat = malloc(num * sizeof(int *));
or better
int** mat = malloc(num * sizeof(*mat));
Also use site_t
for sizes not int
.
I personally would use pointer to array not array of pointers to remove one level of indirection (difficult (de)/allocation , performance penalty)
Always check the result of malloc
and scanf
void *readFile(FILE* fp, size_t *size)
{
if(fscanf(fp, "%d", size) != 1) { /* handle error */}
int (*mat)[*size] = malloc(*size * sizeof(*mat));
if(mat)
{
for(size_t row = 0; row < *size; row++)
{
for(size_t col = 0; col < *size; col++)
{
if(fscanf(fp, "%d", &mat[row][col]) != 1) { /* handle error */}
}
}
}
return mat;
}
void printMatrix (size_t num, int (*mat)[num])
{
if(mat)
{
for(size_t row = 0; row < num; row++)
{
for(size_t col = 0; col < num; col++)
{
printf("%.2d\t", mat[row][col]); /* gdb indicates segfault here */
}
printf("\n");
}
}
}