Reputation: 33
I am kind of new to C programmimg and haven't done anything in a while. I am trying to perform a simple numerical integration of a function. Here is a simplified version of my code:
int main()
{
/*Constants----*/
double e0=8.85E-12; //C^2/Nm^2
double e_charge=1.6E-19; //C
double e_mass=1E-31; //kg
double N=1E22; //m^-3
double w0=1E10; //rad/seg
double gam=5;
double f=(N*pow(e_charge,2))/(e_mass*e0);
/*--------------*/
double delta=50;
double step=0.1;
int array_size=2*delta/step;
double Re_X[array_size];
double Im_X[array_size];
double Re_X_KK[array_size];
double Im_X_KK[array_size];
double i,k;
int j,z;
for(i=w0-delta ; i<=w0+delta ; i=i+step ){
Re_X[j]=f*(pow(w0,2)-pow(i,2))/(pow(pow(w0,2)-pow(i,2),2)+4*pow(i,2)*pow(gam,2));
Im_X[j]=f*(2*i*gam)/(pow(pow(w0,2)-pow(i,2),2)+4*pow(i,2)*pow(gam,2));
j++;
}
/*This is just a test*/
z=0;
for(j=0 ; j<=10 ; j++){
z++;
printf("%d\n",z);
}
return(0);
}
When I run this code nothing works, z does not get printed inside the loop, and the first loop doesn't run as well (I print the results to a .txt and get nothing).
If I comment the second loop the first works just fine. If I comment the first loop the second runs OK. If I dont add one to z in every iteration, everything works.
I really don't understand what is going on, this happens only with integer variables. If I change z to a double, everything is fine (but I need it to be int).
Any help is really apreciated. Thanks!
Upvotes: 2
Views: 69
Reputation: 3256
This program has undefined behavior, since j
is used uninitialized as a subscript to write into Re_X
and Im_X
, which then corrupts memory on the stack. This explains your observations how the program arbitrarily does or does not work when parts of the code are commented. The code being commented is unrelated, but by chance, memory corruption plays out differently between different runs of the program.
A helpful tool to troubleshoot these kinds of errors is AddressSanitizer, enabled in clang or gcc by compiling with -fsanitize=address, or if you are using Xcode, there is an option for it. Another great tool is valgrind.
Upvotes: 1
Reputation: 41017
Use a debugger:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555808 in main () at demo.c:29
29 Im_X[j]=f*(2*i*gam)/(pow(pow(w0,2)-pow(i,2),2)+4*pow(i,2)*pow(gam,2));
(gdb)
You are using an uninititalized variable (j
) in Re_X[j] = ...;
and Im_X[j] = ...;
Upvotes: 3