-1

I am writing a program that multiplies two Matrice's and the third Matrix prints the results. Along with that I want to compute the arithmetic operation time that I specified in my code below, however I keep getting a segmentation fault and I believe I am using the time.h/clock() library function correctly. Ive provided a snippet of the section giving me problems.

    /**  Third Matrix  **/ 
    for (i = 0; i < N; i++) {
        for (x = 0; x < N; x++) {
            arr3[i][x] = 0;
            for (y = 0; y < N; y++)
                arr3[i][x] = arr3[i][x] + arr1[i][y] * arr2[y][x];
        }
    }

    arithmeticBegin = clock(); //begins the clock for arithmetic time

    //the following line is what was causing the seg fault
    arr3[i][x] = arr3[i][x] + arr1[i][y] * arr2[y][x];

    arithmetic_endTime = clock(); //stops the clock for the end of arithmetic time
    /**  The following computers total arithmetic Time **/
    arithmeticTime += (double)(arithmetic_endTime - arithmeticBegin) / CLOCKS_PER_SEC;
Chris
  • 45
  • 6

1 Answers1

2
 //the following line is what was causing the seg fault
  arr3[i][x] = arr3[i][x] + arr1[i][y] * arr2[y][x];

That's because you are accessing the arrays using out of bounds indices for all the arrays.

Remove that line. It does not seem to be doing anything useful.


Couple more observations.

  1. Your computations are likely causing integer overflow since rand() can return anything between [0 - RAND_MAX]. You may want to use a smaller number for the elements of your matrix, such as rand() % 100000.

  2. The printf call creates output without any whitespace between elements. You may want to to add a space between the elements.

     printf ("%4d ", arr3[i][x]);
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Just to be clear, that line is fine in the loop, but when the loop ends `i` and `x` are outside the bounds. – Barmar Apr 03 '18 at 18:31
  • That is there because it is what I am trying to find the computation time of. – Chris Apr 03 '18 at 18:31
  • @Chris You should be getting the computation time of the loop, that's where all the work is. – Barmar Apr 03 '18 at 18:31