I get a segmentation fault when running this code. Anyone know why? Thanks.
#include <stdio.h>
int main()
{
double **m1, **m2, **mr;
int m1_rows, m1_cols, m2_rows, m2_cols, mr_rows, mr_cols;
int i, j, k;
printf("Enter number of rows for matrix 1: ");
scanf("%d", &m1_rows);
printf("Enter number of columns for matrix 1: ");
scanf("%d", &m1_cols);
printf("Enter number of rows for matrix 2: ");
scanf("%d", &m2_rows);
printf("Enter number of columns for matrix 2: ");
scanf("%d", &m2_cols);
//allocate memory for matrix 1 m1
m1 = (double **) calloc(m1_rows, sizeof(double *));
for (i = 0; i < m1_rows; i++) {
m1[i] = (double *) calloc(m1_cols, sizeof(double));
}
//allocate memory for matrix 2 m2
m2 = (double **) calloc(m2_rows, sizeof(double *));
for (i = 0; i < m2_rows; i++) {
m2[i] = (double *) calloc(m2_cols, sizeof(double));
}
//allocate memory for sum matrix mr
mr = (double **) calloc(mr_rows, sizeof(double *));
for (i = 0; i < mr_rows; i++) {
mr[i] = (double *) calloc(mr_cols, sizeof(double));
}
//assign mr_rows and mr_cols
mr_rows = m1_rows;
mr_cols = m2_cols;
//initialize product matrix
for (i = 0; i < m1_rows; i++) {
for (j = 0; j < m2_cols; j++) {
mr[i][j] = 0;
}
}
//perform matrix multiplication
for (i = 0; i < m1_rows; i++) {
for (j = 0; j < m2_cols; j++) {
mr[i][j] = 0;
for (k = 0; k < m1_cols; k++) {
mr[i][j] += m1[i][k] * m2[k][j];
}
}
}
//print result
for (i = 0; i < mr_rows; i++) {
for (j = 0; j < mr_cols; j++) {
printf("%f\t", mr[i][j]);
}
}
//free memory m1
for (i = 0; i < m1_rows; i++); {
free(m1[i]);
}
free(m1);
//free memory m2
for (i = 0; i < m2_rows; i++); {
free(m2[i]);
}
free(m2);
//free memory mr
for (i = 0; i < mr_rows; i++); {
free(mr[i]);
}
free(mr);
return 0;
}
I ran using valgrind valgrind --tool=memcheck a.out for more info on the segmentation fault, but the result was over 30000 errors so it didn’t print them out.
You are not assigning
mr_rowsandmr_cols. They need to be set like this:This line is no good:
That will be accessing elements out of bounds, not least because
kis not initialized. You need that line of code inside three nested for loops. Indeed, you may as well roll the zeroising code into this too.Also, all your memory freeing loops are wrong. Instead of
it should read
That stray semicolon was killing you.
You also need to perform a check that the number of columns in
m1equals the number of rows inm2, i.e. test thatm1_cols == m2_rows.One final point. You duplicate your code horribly here. Don’t have three identical for loops to allocate a matrix and three identical for loops to deallocate. Extract those operations into helper functions which can be called from
main.That’s all that I can find!