title: C - matrix multiplication segmentation fault
body: <p>I get a segmentation fault when running this code.  Anyone know why?  Thanks.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  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", &amp;m1_rows);
  
      printf("Enter number of columns for matrix 1: ");
      scanf("%d", &amp;m1_cols);
  
      printf("Enter number of rows for matrix 2: ");
      scanf("%d", &amp;m2_rows);
  
      printf("Enter number of columns for matrix 2: ");
      scanf("%d", &amp;m2_cols);
  
      //allocate memory for matrix 1 m1
      m1 = (double **) calloc(m1_rows, sizeof(double *));
      for (i = 0; i &lt; 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 &lt; 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 &lt; 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 &lt; m1_rows; i++) {
          for (j = 0; j &lt; m2_cols; j++) {
              mr[i][j] = 0;
          }
      }
  
      //perform matrix multiplication
      for (i = 0; i &lt; m1_rows; i++) {
          for (j = 0; j &lt; m2_cols; j++) {
              mr[i][j] = 0;
              for (k = 0; k &lt; m1_cols; k++) {
                  mr[i][j] += m1[i][k] * m2[k][j];
              }
          }
      }
  
      //print result
      for (i = 0; i &lt; mr_rows; i++) {
          for (j = 0; j &lt; mr_cols; j++) {
              printf("%f\t", mr[i][j]);
          }
      }
  
      //free memory m1
      for (i = 0; i &lt; m1_rows; i++); {
          free(m1[i]);
      }
      free(m1);
  
      //free memory m2
      for (i = 0; i &lt; m2_rows; i++); {
          free(m2[i]);
      }
      free(m2);
  
      //free memory mr
      for (i = 0; i &lt; mr_rows; i++); {
          free(mr[i]);
      }
      free(mr);
  
      return 0;
  }
  </code></pre>
  
  <p>I ran using valgrind <code>valgrind --tool=memcheck a.out</code> for more info on the segmentation fault, but the result was over 30000 errors so it didn't print them out.</p>