问题
I am trying to write an array (2x20000) on C. The test code is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double test( int smod )
{
//
// test subroutine
//
double vect_fma[2][20000];
int i;
// write on file //
FILE *f = fopen("file.txt", "w");
///////////////////
for( i = 1; i < 20001; i = i + 1 ){
// allocate the vector for the fma analysis
vect_fma[1][i] = i*smod;
vect_fma[2][i] = i*smod;
if ( i%smod == 0 )
fprintf(f, "%f %f %f \n", 1.0*i, vect_fma[1][i],vect_fma[2][i] );
}
fclose(f);
return 0;
}
int smod;
void main()
{
smod = 10; // every 10 print the output
test(smod); // call the function
}
I compiled the code with gcc test.c -lm -o test
and I received Segmentation fault (core dumped)
.
As far as I am new on C, I understand that "the compiler tries to store it on the stack" and a solution could be the one presented in the linked page....but that solution looks quite weird (and complex to understand) if compared with more simple fortran declaration of array real(8), dimension(n:m) :: vect_fma
which I can put in a subroutine or in a function without problems.
Is maybe that the declaration I wrote in the code is similar to the fortran real(8), dimension(n,m),allocatable :: vect_fma
one ?
So the question is, it exist a simpler way in C to declare an array inside a function ? Many thanks to everybody.
回答1:
You have out of bounds access in multiple places, which is undefined behaviour.
In C, an array index ranges from 0
to N-1
, not from 1
to N
. That means, rewriting the loop part to:
for( i = 0; i < 20000; i = i + 1 ){
// allocate the vector for the fma analysis
vect_fma[0][i] = i*smod;
vect_fma[1][i] = i*smod;
if ( i%smod == 0 )
fprintf(f, "%f %f %f \n", 1.0*i, vect_fma[0][i],vect_fma[1][i] );
}
It's possible 2x20000 doubles might be too big for the stack size on your system, you'd better off fixing the undefined behaviours first and see if the problem disappears.
回答2:
The problem is your for
loop. You should begin with an iteration where i=0
and end with an iteration where i=19999
. Your code begins with an iteration where i=1
and ends with an iteration where i=20000
.
The problem is that that there is no 20000th element of your array, only a 19999th (zero indexed). When you access the the 20000th element your accessing system memory that was never allocated for your program which is causing a segmentation fault.
Fix your for loop and you should be good.
来源:https://stackoverflow.com/questions/38443757/array-declaration-c-segmentation-fault