在编写算法竞赛习题2.5时,数据无法正常输入到文件data1.out,用gdb调试的时候,报错:
Program received signal SIGSEGV, Segmentation fault.
__chkstk_ms () at …/…/…/src/gcc-6.3.0/libgcc/config/i386/cygwin.S:172
172 …/…/…/src/gcc-6.3.0/libgcc/config/i386/cygwin.S: No such file or directory.
经过调试,发现是给数组分配的空间过大。
void freopenMethod(){
freopen("data1.in", "r", stdin);
freopen("data1.out", "w", stdout);
int a[100000]; // 当给它分配过大空间,会报错Program received signal SIGSEGV, Segmentation fault.__chkstk_ms () at ../../../
int n,m;
int count;
while(scanf("%d", &n)==1){
count = 0;
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
}
scanf("%d", &m);
for(int i=0; i<n;i++){
if(a[i]<m) count++;
}
printf("%d\n", count);
printf("%.3lf\n", (double)clock()/CLOCKS_PER_SEC);
}
}
我猜测这可能和程序内存分配有关,当分配过大数组,导致内存越界。
Segmentation fault的具体研究可看:
https://blog.csdn.net/love_gaohz/article/details/6597857