分段故障 - Strassen的矩阵乘法

时间:2015-11-07 12:02:08

标签: c matrix segmentation-fault strassen

我是新手,我试图实现Strassen算法乘以两个NxN矩阵。我目前正致力于维度。我的N值大于4时出现分段错误。

调试后我发现在第一次调用乘法函数之前和显示两个矩阵之后立即遇到了分段错误。

感谢任何帮助。

非常感谢!

{{1}}

1 个答案:

答案 0 :(得分:2)

您的程序在multiply()中进入无限递归,gdb显示如下堆栈跟踪:

#0  0x0000000000400899 in multiply (m1=..., m2=...) at b.c:60
#1  0x0000000000400fc7 in multiply (m1=..., m2=...) at b.c:140
#2  0x0000000000401584 in multiply (m1=..., m2=...) at b.c:142
#3  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#4  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#5  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#6  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#7  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#8  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#9  0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#10 0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
(...)
#421 0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#422 0x0000000000401859 in multiply (m1=..., m2=...) at b.c:143
#423 0x000000000040067c in main (argc=<optimized out>, argv=<optimized out>) at b.c:43

这可能会导致堆栈溢出,从而导致您发现崩溃。这是第143行的代码:

   140          P1 = multiply(A, sub(F, H));    
   141          P2 = multiply(add(A, B), H);    
   142          P3 = multiply(add(C, D), E);
   143          P4 = multiply(D, sub(G, E));
   144          P5 = multiply(add(A, D), add(E, H));
   145          P6 = multiply(sub(B, D), add(G, H));
   146          P7 = multiply(sub(A,C), add(E, F));

我怀疑用于计算子阵列大小的逻辑是错误的。进一步挖掘表明m2在递归调用中具有维度,您应该进行一些进一步的调试以找出究竟出错的地方。

我的编译器警告的另一个问题是:

b.c: In function 'multiply':
b.c:166:28: warning: array subscript is above array bounds [-Warray-bounds]
                 result.a[i][j] = R2.a[m1_i][m1_j];
                            ^
b.c:178:28: warning: array subscript is above array bounds [-Warray-bounds]
                 result.a[i][j] = R4.a[m1_i][m1_j];

以下是相应的源代码行:

   163          for(m1_i=R2.rs, i=0; m1_i<=R2.re; m1_i++, i++)
   164          {
   165              for(m1_j=R2.cs, j=dimension/2; m1_j<=R2.ce; m1_j++, j++)
   166                  result.a[i][j] = R2.a[m1_i][m1_j];
   167          }
...
   175          for(m1_i=R4.rs, i=dimension/2; m1_i<=R4.re; m1_i++, i++)
   176          {
   177              for(m1_j=R4.cs, j=dimension/2; m1_j<=R4.ce; m1_j++, j++)
   178                  result.a[i][j] = R4.a[m1_i][m1_j];
   179          }