I've got a simple C program to run some matrix matrix multiplication for some tests:
我有一个简单的C程序来运行一些矩阵矩阵乘法进行一些测试:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000
#define R_M 100
void disp_matrix(double A[N][N]);
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
int seed = 1;
srand(seed);
double A[N][N];
double B[N][N];
double C[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
A[i][j] = (double)rand()/(double)(RAND_MAX/R_M);
B[i][j] = (double)rand()/(double)(RAND_MAX/R_M);
C[i][j] = 0.;
}
}
for(int i = 0; i < N; i++){
for(int k = 0; k < N; k++){
for(int j = 0; j < N; j++){
C[i][k] += A[i][j] * B[j][k];
}
}
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time spent: %f\n", time_spent );
/* disp_matrix(C); */
return 0;
}
void disp_matrix(double A[N][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
printf("%10.3g",A[i][j]);
}
printf("\n");
}
return;
}
If I compile with:
如果我编译:
gcc -Wall -std=c11 -O2 test.c -o test && ./test
The program will run fine, however, if I run:
程序运行正常,但是,如果我运行:
gcc -Wall -std=c11 test.c -o test && ./test
/bin/bash: Zeile 1: 10617 Speicherzugriffsfehler ./test
C will compile fine, but the execution of the program gives me an segmentation fault (Speicherzugriffsfehler). I really can not figure out why it would do it this way.
C将编译正常,但程序的执行给我一个分段错误(Speicherzugriffsfehler)。我真的无法弄清楚为什么会这样做。
Why does the optimization "fix" my program and where is the original error. I should have plenty of memory for arrays of such a small size.
为什么优化“修复”我的程序以及原始错误在哪里。对于如此小的数组,我应该有足够的内存。
2 个解决方案
#1
1
The root of the problem is the huge arrays on the stack, resulting a stack overflow, leading to a seg fault event,
问题的根源是堆栈上的巨大数组,导致堆栈溢出,导致seg错误事件,
Suggest move the arrays to file scope from their current main() function scope.
建议将数组从其当前的main()函数范围移动到文件范围。
#2
1
As suggested in some of the comments, the array was to big for a static definition. I used malloc() and it worked fine.
正如一些评论中所建议的那样,数组对于静态定义来说很重要。我使用了malloc(),它运行良好。
Edit: Also,(as commented) the optimiziation 'fixes' my program, because I don't use C and it is therefore not calculated.
编辑:另外,(评论)优化'修复'我的程序,因为我不使用C,因此不计算。
#1
1
The root of the problem is the huge arrays on the stack, resulting a stack overflow, leading to a seg fault event,
问题的根源是堆栈上的巨大数组,导致堆栈溢出,导致seg错误事件,
Suggest move the arrays to file scope from their current main() function scope.
建议将数组从其当前的main()函数范围移动到文件范围。
#2
1
As suggested in some of the comments, the array was to big for a static definition. I used malloc() and it worked fine.
正如一些评论中所建议的那样,数组对于静态定义来说很重要。我使用了malloc(),它运行良好。
Edit: Also,(as commented) the optimiziation 'fixes' my program, because I don't use C and it is therefore not calculated.
编辑:另外,(评论)优化'修复'我的程序,因为我不使用C,因此不计算。