I have some C code and I just verified after a painstaking effort doing things manually in Excel that my executable compiled via gcc -O0
runs correctly but if I compile with -O2
my output is bad.
What might cause this? I've tracked down the problem so far to where it reads in the data, that is for the total set of input files that it reads from, every line of data (numbers from a text file) that I read I immediately print to standard output and redirect into a file called either O0.txt or O2.txt. If I compare these files, I see significant differences in numbers when I expect to see the exact same.
this is gcc-4.3.4 suse linux
here is a snippet of the code to show what is not working with -O2 but it does work with -O0 based on the printf
and redirecting output to either O0.txt
or O2.txt
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
# define ZZ 8192
double x[9000];
double y[9000];
double z[2][17][20][3600];
void Read_Data ( FILE *fp, const int R, const int S, const int T, const int type, const int M )
{
char line[ZZ];
int count;
double a, b, c, d, e, f, g, h;
for ( r = 0; r < 12; r++ ) /* skip past header */
fgets( line, LS, fp );
for ( r = 0; r < R; r++ )
{
for ( s = 0; s < S; s++ )
{
for ( t = 0; t < T; t++ )
{
sscanf( line, "%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &a, &b, &c, &d, &e, &f, &g, &h );
if (( a == 0 ) && ( b == 0 ))
x[t] = 1e-9;
else
x[t] = a*a + b*b;
if (( g == 0 ) && ( h == 0 ))
y[t] = 1e-9;
else
y[t] = g*g + h*h;
printf("%18.12e %18.12e %18.12e %18.12e\n", a, b, c, d );
fgets( line, ZZ, fp );
}
if ( type == 1 )
{
z[0][M][r][s] = Find_Median( x, T );
z[1][M][r][s] = Find_Median( y, T );
}
else if ( type == 2 )
{
sum_x = 0; sumy = 0;
for ( tt = 0; tt < T; tt+ )
{
sumx += x[tt];
sumy += y[tt];
}
z[0][M][r][s] = sumx / ((double)T);
z[1][M][r][s] = sumy / ((double)T);
}
}
}
}
int main ( int argc, char *argv[] )
{
FILE *fpi;
Parse_Command_line( argc, argv );
/* other code here */
T has value of 10
S has value of 10
R has value of 180
/* other code here */
fpi = fopen("mydata", "r" );
for ( m = 0; m < 17; m++ )
{
Read_Data( fpi, R, S, T, m);
}
/* other code here */
return 0;
}