我的教授发出测试代码以运行我们的程序。但是,测试代码本身在编译时会出现分段错误错误。错误发生在第一个printf上。但是,如果该行被注释掉,它就会出现在下一行。这听起来像代码对他来说很好,所以我想弄清楚为什么它失败了。我知道他在使用C ++时正在使用C,但即使我尝试使用gcc而不是g ++编译测试代码,它仍然会失败。有人知道我为什么会遇到问题吗?谢谢!代码如下。
#include <stdio.h>
main()
{ double A[400000][4], b[400000], c[4] ;
double result[4];
int i, j; double s, t;
printf("Preparing test: 4 variables, 400000 inequalities\n");
A[0][0] = 1.0; A[0][1] = 2.0; A[0][2] = 1.0; A[0][3] = 0.0; b[0] = 10000.0;
A[1][0] = 0.0; A[1][1] = 1.0; A[1][2] = 2.0; A[1][3] = 1.0; b[0] = 10000.0;
A[2][0] = 1.0; A[2][1] = 0.0; A[2][2] = 1.0; A[2][3] = 3.0; b[0] = 10000.0;
A[3][0] = 4.0; A[3][1] = 0.0; A[3][2] = 1.0; A[3][3] = 1.0; b[0] = 10000.0;
c[0]=1.0; c[1]=1.0; c[2]=1.0; c[3]=1.0;
for( i=4; i< 100000; i++ )
{ A[i][0] = (12123*i)%104729;
A[i][1] = (47*i)%104729;
A[i][2] = (2011*i)%104729;
A[i][3] = (7919*i)%104729;
b[i] = A[i][0] + 2*A[i][1] + 3*A[i][2] + 4* A[i][3] + 1 + (i%137);
}
A[100000][0] = 0.0; A[100000][1] = 6.0; A[100000][2] = 1.0;
A[100000][3] = 1.0; b[100000] = 19.0;
for( i=100001; i< 200000; i++ )
{ A[i][0] = (2323*i)%101111;
A[i][1] = (74*i)%101111;
A[i][2] = (2017*i)%101111;
A[i][3] = (7915*i)%101111;
b[i] = A[i][0] + 2*A[i][1] + 3*A[i][2] + 4* A[i][3] + 2 + (i%89);
}
A[200000][0] = 5.0; A[200000][1] = 2.0; A[200000][2] = 0.0;
A[200000][3] = 1.0; b[200000] = 11.0;
for( i=200001; i< 300000; i++ )
{ A[i][0] = (23123*i)%100003;
A[i][1] = (47*i)%100003;
A[i][2] = (2011*i)%100003;
A[i][3] = (7919*i)%100003;
b[i] = A[i][0] + 2*A[i][1] + 3*A[i][2] + 4* A[i][3] + 2 + (i%57);
}
A[300000][0] = 1.0; A[300000][1] = 2.0; A[300000][2] = 1.0;
A[300000][3] = 3.0; b[300000] = 20.0;
A[300001][0] = 1.0; A[300001][1] = 0.0; A[300001][2] = 5.0;
A[300001][3] = 4.0; b[300001] = 32.0;
A[300002][0] = 7.0; A[300002][1] = 1.0; A[300002][2] = 1.0;
A[300002][3] = 7.0; b[300002] = 40.0;
for( i=300003; i< 400000; i++ )
{ A[i][0] = (13*i)%103087;
A[i][1] = (99*i)%103087;
A[i][2] = (2012*i)%103087;
A[i][3] = (666*i)%103087;
b[i] = A[i][0] + 2*A[i][1] + 3*A[i][2] + 4* A[i][3] + 1;
}
printf("Running test: 400000 inequalities, 4 variables\n");
//j = rand_lp(40, &(A[0][0]), &(b[0]), &(c[0]), &(result[0]));
printf("Test: extremal point (%f, %f, %f, %f) after %d recomputation steps\n",
result[0], result[1], result[2], result[3], j);
printf("Answer should be (1,2,3,4)\n End Test\n");
}
答案 0 :(得分:18)
尝试改变:
double A[400000][4], b[400000], c[4] ;
到
static double A[400000][4], b[400000], c[4] ;
您对A
数组的声明具有自动存储持续时间,这可能意味着您的系统存储在堆栈中。您的进程的总堆栈可能低于该堆栈,并且您遇到堆栈溢出。
在Linux上,您可以运行ulimit
命令:
$ ulimit -s
8192
$
查看为进程分配的堆栈大小(KB)。例如,我机器上的8192 kB。
答案 1 :(得分:12)
你已经超出了堆栈的限制。你的教授在main
的堆栈框架中声明了15MB的数据。那太大了。
由于在main顶部声明的ojbect的生命周期基本上是整个程序,因此只需将对象声明为static
。这样他们就会处于(相对无限的)数据段,并且具有几乎相同的生命周期。
尝试更改此行:
double A[400000][4], b[400000], c[4] ;
到此:
static double A[400000][4], b[400000], c[4] ;