【问题标题】:Seg fault when trying to compute Arithmetic Operation Time in C尝试在 C 中计算算术运算时间时出现 Seg 错误
【发布时间】:2018-04-03 18:11:25
【问题描述】:

我正在编写一个程序,将两个矩阵相乘,第三个矩阵打印结果。除此之外,我想计算我在下面的代码中指定的算术运算时间,但是我不断遇到分段错误,我相信我正确使用了 time.h/clock() 库函数。我提供了给我问题的部分的 sn-p。

    /**  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;

【问题讨论】:

  • 没有minimal reproducible example 就无法回答。
  • @FredLarson 我已经添加了完整的代码。
  • 程序中的什么地方出现了分段错误?使用 gdb 查找。
  • @ArndtJonasson 我已经评论了导致分段错误的行。

标签: c segmentation-fault malloc clock time.h


【解决方案1】:
 //the following line is what was causing the seg fault
  arr3[i][x] = arr3[i][x] + arr1[i][y] * arr2[y][x];

这是因为您正在使用所有数组的越界索引访问数组。

删除该行。它似乎没有做任何有用的事情。


结合更多观察。

  1. 您的计算可能导致整数溢出,因为rand() 可以返回介于[0 - RAND_MAX] 之间的任何值。您可能希望为矩阵的元素使用较小的数字,例如 rand() % 100000

  2. printf 调用创建的输出在元素之间没有任何空格。您可能希望在元素之间添加一个空格。

     printf ("%4d ", arr3[i][x]);
    

【讨论】:

  • 明确一点,循环中的那条线没问题,但是当循环结束时,ix 超出了界限。
  • 那是因为它是我试图找到的计算时间。
  • @Chris 你应该得到循环的计算时间,这就是所有工作所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多