Run time error C program - c

I'm trying to run a simple program involving large data sets and analyzing them. The program is quite simple and it gives no error in compilation. however while running it just stops working. I'm an amateur programmer with only basic C knowledge. I'm guessing here that somehow some datatype limit is being exceeded because of the large data. Any help is appreciated !
here's the code:
#include <stdio.h>
#include<math.h>
int main()
{
int i,n;
n=193704;
// original data set arrays
double xcor[193706],ycor[193706],zcor[193706],decibel[193706],frequency[193706],node[193706];
// new data set arrays
double xcor1[193706], ycor1[193706], zcor1[193706], decibel1[193706], frequency1[193706], node1[193706];
// equating all values of modified arrays to zero for future comparison
for(i=0;i<n;i++)
{
xcor1[i]=0;
ycor1[i]=0;
zcor1[i]=0;
decibel1[i]=0;
frequency1[i]=0;
node1[i]=0;
}
//FILE POINTERS DEFINED HERE
FILE *acdb, *freq, *nodes, *xcord, *ycord, *zcord, *hearfreq, *heardb, *hearx, *heary, *hearz ;
acdb=(fopen("acousticdb.txt","r"));
freq=(fopen("frequency.txt","r"));
nodes=(fopen("node.txt","r"));
xcord=(fopen("xcor.txt","r"));
ycord=(fopen("ycor.txt","r"));
zcord=(fopen("zcor.txt","r"));
hearfreq=(fopen("hearingrangefrequency.txt","w"));
heardb=(fopen("hearingrangedecibel.txt","w"));
hearx=(fopen("hearing-x.txt","w"));
heary=(fopen("hearing-y.txt","w"));
hearz=(fopen("hearing-z.txt","w"));
for(i=0;i<n;++i)
{
fscanf(acdb, "%lf", &decibel[i]);
fscanf(freq, "%lf", &frequency[i]);
fscanf(nodes, "%lf", &node[i]);
fscanf(xcord, "%lf", &xcor[i]);
fscanf(ycord, "%lf", &ycor[i]);
fscanf(zcord, "%lf", &zcor[i]);
}
fclose(acdb);
fclose(freq);
fclose(nodes);
fclose(xcord);
fclose(ycord);
fclose(zcord);
// checking frequecy within hearing range
for(i=0;i<n;i++)
{
if(frequency[i]<20000 && frequency[i]>20 )
{
xcor[i]=xcor1[i];
ycor[i]=ycor1[i];
zcor[i]=zcor1[i];
decibel[i]=decibel1[i];
frequency[i]=frequency1[i];
node[i]=node1[i];
}
}
//wiriting values in text file
for(i=0;i<n;i++)
{
fprintf(hearfreq," %lf \n", frequency1[i]);
fprintf(heardb," %lf \n", decibel1[i]);
fprintf(hearx," %lf \n", xcor1[i]);
fprintf(heary," %lf \n", ycor1[i]);
fprintf(hearz," %lf \n", zcor1[i]);
}
return 0;
}

You probably run out of stack space. But if I look at the code then there is no need to first read all the data into arrays: all calculations are on a single index (i) and so you can just read one data item from each file, check if they are within hearing frequency and write them out:
int main()
{
int i, n=193704;
// original data set arrays
double xcor,ycor,zcor,decibel,frequency,node;
// new data set arrays
double xcor1, ycor1, zcor1, decibel1, frequency1, node1;
//FILE POINTERS DEFINED HERE
FILE *acdb, *freq, *nodes, *xcord, *ycord, *zcord, *hearfreq, *heardb, *hearx, *heary, *hearz ;
acdb=(fopen("acousticdb.txt","r"));
freq=(fopen("frequency.txt","r"));
nodes=(fopen("node.txt","r"));
xcord=(fopen("xcor.txt","r"));
ycord=(fopen("ycor.txt","r"));
zcord=(fopen("zcor.txt","r"));
hearfreq=(fopen("hearingrangefrequency.txt","w"));
heardb=(fopen("hearingrangedecibel.txt","w"));
hearx=(fopen("hearing-x.txt","w"));
heary=(fopen("hearing-y.txt","w"));
hearz=(fopen("hearing-z.txt","w"));
for(i=0;i<n;++i)
{
fscanf(acdb, "%lf", &decibel);
fscanf(freq, "%lf", &frequency);
fscanf(nodes, "%lf", &node);
fscanf(xcord, "%lf", &xcor);
fscanf(ycord, "%lf", &ycor);
fscanf(zcord, "%lf", &zcor);
// checking frequecy within hearing range
if(frequency<20000 && frequency>20 )
{
xcor=xcor1;
ycor=ycor1;
zcor=zcor1;
decibel=decibel1;
frequency=frequency1;
node=node1;
}
else xcor1= ycor1= zcor1= decibel1= frequency1= node1= 0.0;
//wiriting values in text file
fprintf(hearfreq," %lf \n", frequency1);
fprintf(heardb," %lf \n", decibel1);
fprintf(hearx," %lf \n", xcor1);
fprintf(heary," %lf \n", ycor1);
fprintf(hearz," %lf \n", zcor1);
}
fclose(acdb);
fclose(freq);
fclose(nodes);
fclose(xcord);
fclose(ycord);
fclose(zcord);
// don't forget to close these
fclose(hearfreq);
fclose(heardb);
fclose(hearx);
fclose(heary);
fclose(hearz);
return 0;
}

If you declare arrays like this
double xcor1[193706];
without dynamic memory allocation using malloc() or similar, you are reserving that space on the stack. Considering you are doing more then 1 million double elements on your stack, it is probably overflowing. You have a literal stack overflow.
Quips aside, use dynamic memory allocation for such big arrays.
It works like this:
double* xcor1 = malloc(sizeof(double) * 193706) ;
And when you're all done with it, don't forget to free it, too.
free(xcor1);
Ofcourse, with your code, you can also just not use arrays alltogether and not save the data in between, and instead use single variables for your operations.

Related

How to read imaginary data from text file, with C

I am unable to read imaginary data from text file.
Here is my .txt file
abc.txt
0.2e-3+0.3*I 0.1+0.1*I
0.3+0.1*I 0.1+0.4*I
I want to read this data into a matrix and print it.
I found the solutions using C++ here and here. I don't know how to do the same in C.
I am able to read decimal and integer data in .txt and print them.
I am also able to print imaginary data initialized at the declaration, using complex.h header. This is the program I have writtern
#include<stdio.h>
#include<stdlib.h>
#include<complex.h>
#include<math.h>
int M,N,i,j,k,l,p,q;
int b[2];
int main(void)
{
FILE* ptr = fopen("abc.txt", "r");
if (ptr == NULL) {
printf("no such file.");
return 0;
}
long double d=0.2e-3+0.3*I;
long double c=0.0000000600415046630252;
double matrixA[2][2];
for(i=0;i<2; i++)
for(j=0;j<2; j++)
fscanf(ptr,"%lf+i%lf\n", creal(&matrixA[i][j]), cimag(&matrixA[i][j]));
//fscanf(ptr, "%lf", &matrixA[i][j]) for reading non-imainary data, It worked.
for(i=0;i<2; i++)
for(j=0;j<2; j++)
printf("%f+i%f\n", creal(matrixA[i][j]), cimag(matrixA[i][j]));
//printf("%lf\n", matrixA[i][j]); for printing non-imainary data, It worked.
printf("%f+i%f\n", creal(d), cimag(d));
printf("%Lg\n",c);
fclose(ptr);
return 0;
}
But I want to read it from the text, because I have an array of larger size, which I can't initialize at declaration, because of it's size.
There are two main issues with your code:
You need to add complex to the variables that hold complex values.
scanf() needs pointers to objects to store scanned values in them. But creal() returns a value, copied from its argument's contents. It is neither a pointer, nor could you get the address of the corresponding part of the complex argument.
Therefore, you need to provide temporary objects to scanf() which receive the scanned values. After successfully scanning, these values are combined to a complex value and assigned to the indexed matrix cell.
Minor issues not contributing to the core problem are:
The given source is "augmented" with unneeded #includes, unused variables, global variables, and experiments with constants. I removed them all to see the real thing.
The specifier "%f" (as many others) lets scanf() skip whitespace like blanks, tabs, newlines, and so on. Providing a "\n" mostly does more harm than one would expect.
I kept the "*I" to check the correct format. However, an error will only be found on the next call of scanf(), when it cannot scan the next number.
You need to check the return value of scanf(), always! It returns the number of conversions that were successful.
It is a common and good habit to let the compiler calculate the number of elements in an array. Divide the total size by an element's size.
Oh, and sizeof is an operator, not a function.
It is also best to return symbolic values to the caller, instead of magic numbers. Fortunately, the standard library defines these EXIT_... macros.
The signs are correctly handled by scanf() already. There is no need to tell it more. But for a nice output with printf(), you use the "+" as a flag to always output a sign.
Since the sign is now placed directly before the number, I moved the multiplication by I (you can change it to lower case, if you want) to the back of the imaginary part. This also matches the input format.
Error output is done via stderr instead of stdout. For example, this enables you to redirect the standard output to a pipe or file, without missing potential errors. You can also redirect errors somewhere else. And it is a well-known and appreciated standard.
This is a possible solution:
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
int main(void)
{
FILE* ptr = fopen("abc.txt", "r");
if (ptr == NULL) {
perror("\"abc.txt\"");
return EXIT_FAILURE;
}
double complex matrixA[2][2];
for (size_t i = 0; i < sizeof matrixA / sizeof matrixA[0]; i++)
for (size_t j = 0; j < sizeof matrixA[0] / sizeof matrixA[0][0]; j++) {
double real;
double imag;
if (fscanf(ptr, "%lf%lf*I", &real, &imag) != 2) {
fclose(ptr);
fprintf(stderr, "Wrong input format\n");
return EXIT_FAILURE;
}
matrixA[i][j] = real + imag * I;
}
fclose(ptr);
for (size_t i = 0; i < sizeof matrixA / sizeof matrixA[0]; i++)
for (size_t j = 0; j < sizeof matrixA[0] / sizeof matrixA[0][0]; j++)
printf("%+f%+f*I\n", creal(matrixA[i][j]), cimag(matrixA[i][j]));
return EXIT_SUCCESS;
}
Here's a simple solution using scanf() and the format shown in the examples.
It writes the values in the same format that it reads them — the output can be scanned by the program as input.
/* SO 7438-4793 */
#include <stdio.h>
static int read_complex(FILE *fp, double *r, double *i)
{
int offset = 0;
char sign[2];
if (fscanf(fp, "%lg%[-+]%lg*%*[iI]%n", r, sign, i, &offset) != 3 || offset == 0)
return EOF;
if (sign[0] == '-')
*i = -*i;
return 0;
}
int main(void)
{
double r;
double i;
while (read_complex(stdin, &r, &i) == 0)
printf("%g%+g*I\n", r, i);
return 0;
}
Sample input:
0.2e-3+0.3*I 0.1+0.1*I
0.3+0.1*I 0.1+0.4*I
-1.2-3.6*I -6.02214076e23-6.62607015E-34*I
Output from sample input:
0.0002+0.3*I
0.1+0.1*I
0.3+0.1*I
0.1+0.4*I
-1.2-3.6*I
-6.02214e+23-6.62607e-34*I
The numbers at the end with large exponents are Avogadro's Number and the Planck Constant.
The format is about as stringent are you can make it with scanf(), but, although it requires a sign (+ or -) between the real and imaginary parts and requires the * and I to be immediately after the imaginary part (and the conversion will fail if the *I is missing), and accepts either i or I to indicate the imaginary value:
It doesn't stop the imaginary number having a second sign (so it will read a value such as "-6+-4*I").
It doesn't stop there being white space after the mandatory sign (so it will read a value such as "-6+ 24*I".
It doesn't stop the real part being on one line and the imaginary part on the next line.
It won't handle either a pure-real number or a pure-imaginary number properly.
The scanf() functions are very flexible about white space, and it is very hard to prevent them from accepting white space. It would require a custom parser to prevent unwanted spaces. You could do that by reading the numbers and the markers separately, as strings, and then verifying that there's no space and so on. That might be the best way to handle it. You'd use sscanf() to convert the string read after ensuring there's no embedded white space yet the format is correct.
I do not know which IDE you are using for C, so I do not understand this ./testprog <test.data.
I have yet to find an IDE that does not drive me bonkers. I use a Unix shell running in a terminal window. Assuming that your program name is testprog and the data file is test.data, typing ./testprog < test.data runs the program and feeds the contents of test.data as its standard input. On Windows, this would be a command window (and I think PowerShell would work much the same way).
I used fgets to read each line of the text file. Though I know the functionality of sscanf, I do not know how to parse an entire line, which has about 23 elements per line. If the number of elements in a line are few, I know how to parse it. Could you help me about it?
As I noted in a comment, the SO Q&A How to use sscanf() in loops? explains how to use sscanf() to read multiple entries from a line. In this case, you will need to read multiple complex numbers from a single line. Here is some code that shows it at work. It uses the POSIX getline() function to read arbitrarily long lines. If it isn't available to you, you can use fgets() instead, but you'll need to preallocate a big enough line buffer.
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#ifndef CMPLX
#define CMPLX(r, i) ((double complex)((double)(r) + I * (double)(i)))
#endif
static size_t scan_multi_complex(const char *string, size_t nvalues,
complex double *v, const char **eoc)
{
size_t nread = 0;
const char *buffer = string;
while (nread < nvalues)
{
int offset = 0;
char sign[2];
double r, i;
if (sscanf(buffer, "%lg%[-+]%lg*%*[iI]%n", &r, sign, &i, &offset) != 3 || offset == 0)
break;
if (sign[0] == '-')
i = -i;
v[nread++] = CMPLX(r, i);
buffer += offset;
}
*eoc = buffer;
return nread;
}
static void dump_complex(size_t nvalues, complex double values[nvalues])
{
for (size_t i = 0; i < nvalues; i++)
printf("%g%+g*I\n", creal(values[i]), cimag(values[i]));
}
enum { NUM_VALUES = 128 };
int main(void)
{
double complex values[NUM_VALUES];
size_t nvalues = 0;
char *buffer = 0;
size_t buflen = 0;
int length;
size_t lineno = 0;
while ((length = getline(&buffer, &buflen, stdin)) > 0 && nvalues < NUM_VALUES)
{
const char *eoc;
printf("Line: %zu [[%.*s]]\n", ++lineno, length - 1, buffer);
size_t nread = scan_multi_complex(buffer, NUM_VALUES - nvalues, &values[nvalues], &eoc);
if (*eoc != '\0' && *eoc != '\n')
printf("EOC: [[%s]]\n", eoc);
if (nread == 0)
break;
dump_complex(nread, &values[nvalues]);
nvalues += nread;
}
free(buffer);
printf("All done:\n");
dump_complex(nvalues, values);
return 0;
}
Here is a data file with 8 lines with 10 complex numbers per line):
-1.95+11.00*I +21.72+64.12*I -95.16-1.81*I +64.23+64.55*I +28.42-29.29*I -49.25+7.87*I +44.98+79.62*I +69.80-1.24*I +61.99+37.01*I +72.43+56.88*I
-9.15+31.41*I +63.84-15.82*I -0.77-76.80*I -85.59+74.86*I +93.00-35.10*I -93.82+52.80*I +85.45+82.42*I +0.67-55.77*I -58.32+72.63*I -27.66-81.15*I
+87.97+9.03*I +7.05-74.91*I +27.60+65.89*I +49.81+25.08*I +44.33+77.00*I +93.27-7.74*I +61.62-5.01*I +99.33-82.80*I +8.83+62.96*I +7.45+73.70*I
+40.99-12.44*I +53.34+21.74*I +75.77-62.56*I +54.16-26.97*I -37.02-31.93*I +78.20-20.91*I +79.64+74.71*I +67.95-40.73*I +58.19+61.25*I +62.29-22.43*I
+47.36-16.19*I +68.48-15.00*I +6.85+61.50*I -6.62+55.18*I +34.95-69.81*I -88.62-81.15*I +75.92-74.65*I +85.17-3.84*I -37.20-96.98*I +74.97+78.88*I
+56.80+63.63*I +92.83-16.18*I -11.47+8.81*I +90.74+42.86*I +19.11-56.70*I -77.93-70.47*I +6.73+86.12*I +2.70-57.93*I +57.87+29.44*I +6.65-63.09*I
-35.35-70.67*I +8.08-21.82*I +86.72-93.82*I -28.96-24.69*I +68.73-15.36*I +52.85+94.65*I +85.07-84.04*I +9.98+29.56*I -78.01-81.23*I -10.67+13.68*I
+83.10-33.86*I +56.87+30.23*I -78.56+3.73*I +31.41+10.30*I +91.98+29.04*I -9.20+24.59*I +70.82-19.41*I +29.21+84.74*I +56.62+92.29*I +70.66-48.35*I
The output of the program is:
Line: 1 [[-1.95+11.00*I +21.72+64.12*I -95.16-1.81*I +64.23+64.55*I +28.42-29.29*I -49.25+7.87*I +44.98+79.62*I +69.80-1.24*I +61.99+37.01*I +72.43+56.88*I]]
-1.95+11*I
21.72+64.12*I
-95.16-1.81*I
64.23+64.55*I
28.42-29.29*I
-49.25+7.87*I
44.98+79.62*I
69.8-1.24*I
61.99+37.01*I
72.43+56.88*I
Line: 2 [[-9.15+31.41*I +63.84-15.82*I -0.77-76.80*I -85.59+74.86*I +93.00-35.10*I -93.82+52.80*I +85.45+82.42*I +0.67-55.77*I -58.32+72.63*I -27.66-81.15*I]]
-9.15+31.41*I
63.84-15.82*I
-0.77-76.8*I
-85.59+74.86*I
93-35.1*I
-93.82+52.8*I
85.45+82.42*I
0.67-55.77*I
-58.32+72.63*I
-27.66-81.15*I
Line: 3 [[+87.97+9.03*I +7.05-74.91*I +27.60+65.89*I +49.81+25.08*I +44.33+77.00*I +93.27-7.74*I +61.62-5.01*I +99.33-82.80*I +8.83+62.96*I +7.45+73.70*I]]
87.97+9.03*I
7.05-74.91*I
27.6+65.89*I
49.81+25.08*I
44.33+77*I
93.27-7.74*I
61.62-5.01*I
99.33-82.8*I
8.83+62.96*I
7.45+73.7*I
Line: 4 [[+40.99-12.44*I +53.34+21.74*I +75.77-62.56*I +54.16-26.97*I -37.02-31.93*I +78.20-20.91*I +79.64+74.71*I +67.95-40.73*I +58.19+61.25*I +62.29-22.43*I]]
40.99-12.44*I
53.34+21.74*I
75.77-62.56*I
54.16-26.97*I
-37.02-31.93*I
78.2-20.91*I
79.64+74.71*I
67.95-40.73*I
58.19+61.25*I
62.29-22.43*I
Line: 5 [[+47.36-16.19*I +68.48-15.00*I +6.85+61.50*I -6.62+55.18*I +34.95-69.81*I -88.62-81.15*I +75.92-74.65*I +85.17-3.84*I -37.20-96.98*I +74.97+78.88*I]]
47.36-16.19*I
68.48-15*I
6.85+61.5*I
-6.62+55.18*I
34.95-69.81*I
-88.62-81.15*I
75.92-74.65*I
85.17-3.84*I
-37.2-96.98*I
74.97+78.88*I
Line: 6 [[+56.80+63.63*I +92.83-16.18*I -11.47+8.81*I +90.74+42.86*I +19.11-56.70*I -77.93-70.47*I +6.73+86.12*I +2.70-57.93*I +57.87+29.44*I +6.65-63.09*I]]
56.8+63.63*I
92.83-16.18*I
-11.47+8.81*I
90.74+42.86*I
19.11-56.7*I
-77.93-70.47*I
6.73+86.12*I
2.7-57.93*I
57.87+29.44*I
6.65-63.09*I
Line: 7 [[-35.35-70.67*I +8.08-21.82*I +86.72-93.82*I -28.96-24.69*I +68.73-15.36*I +52.85+94.65*I +85.07-84.04*I +9.98+29.56*I -78.01-81.23*I -10.67+13.68*I]]
-35.35-70.67*I
8.08-21.82*I
86.72-93.82*I
-28.96-24.69*I
68.73-15.36*I
52.85+94.65*I
85.07-84.04*I
9.98+29.56*I
-78.01-81.23*I
-10.67+13.68*I
Line: 8 [[+83.10-33.86*I +56.87+30.23*I -78.56+3.73*I +31.41+10.30*I +91.98+29.04*I -9.20+24.59*I +70.82-19.41*I +29.21+84.74*I +56.62+92.29*I +70.66-48.35*I]]
83.1-33.86*I
56.87+30.23*I
-78.56+3.73*I
31.41+10.3*I
91.98+29.04*I
-9.2+24.59*I
70.82-19.41*I
29.21+84.74*I
56.62+92.29*I
70.66-48.35*I
All done:
-1.95+11*I
21.72+64.12*I
-95.16-1.81*I
64.23+64.55*I
28.42-29.29*I
-49.25+7.87*I
44.98+79.62*I
69.8-1.24*I
61.99+37.01*I
72.43+56.88*I
-9.15+31.41*I
63.84-15.82*I
-0.77-76.8*I
-85.59+74.86*I
93-35.1*I
-93.82+52.8*I
85.45+82.42*I
0.67-55.77*I
-58.32+72.63*I
-27.66-81.15*I
87.97+9.03*I
7.05-74.91*I
27.6+65.89*I
49.81+25.08*I
44.33+77*I
93.27-7.74*I
61.62-5.01*I
99.33-82.8*I
8.83+62.96*I
7.45+73.7*I
40.99-12.44*I
53.34+21.74*I
75.77-62.56*I
54.16-26.97*I
-37.02-31.93*I
78.2-20.91*I
79.64+74.71*I
67.95-40.73*I
58.19+61.25*I
62.29-22.43*I
47.36-16.19*I
68.48-15*I
6.85+61.5*I
-6.62+55.18*I
34.95-69.81*I
-88.62-81.15*I
75.92-74.65*I
85.17-3.84*I
-37.2-96.98*I
74.97+78.88*I
56.8+63.63*I
92.83-16.18*I
-11.47+8.81*I
90.74+42.86*I
19.11-56.7*I
-77.93-70.47*I
6.73+86.12*I
2.7-57.93*I
57.87+29.44*I
6.65-63.09*I
-35.35-70.67*I
8.08-21.82*I
86.72-93.82*I
-28.96-24.69*I
68.73-15.36*I
52.85+94.65*I
85.07-84.04*I
9.98+29.56*I
-78.01-81.23*I
-10.67+13.68*I
83.1-33.86*I
56.87+30.23*I
-78.56+3.73*I
31.41+10.3*I
91.98+29.04*I
-9.2+24.59*I
70.82-19.41*I
29.21+84.74*I
56.62+92.29*I
70.66-48.35*I
The code would handle lines with any number of entries on a line (up to 128 in total because of the limit on the size of the array of complex numbers — but that can be fixed too.

Scanning numbers from a file line to line and stopping at some point (C)

I have a file (input.dat) with several lines, each of which has 4 numbers. I want to write a script in C that reads the numbers on line 10, which I will save as var_i_10 (with i=1,2,3,4). Then, I want it to check line by line until the 2nd number is 5% lower than var_2_10. At that point, I want the program to write down the line where it has stopped on another file (output.dat).
This is what I've come up with:
#include <stdio.h>
int main(void) {
FILE *Fdata; //The file with the data
FILE *Foutput; //The file I want to write the final result
float *var_1, *var_2, *var_3, *var_4, *var_1_10, *var_2_10, *var_3_10, *var_4_10; //The variables in input.dat
int i; //The line number
Fdata=fopen("input.dat","r");
Foutput = fopen("output.dat","w+");
for (i = 0; i < 10; i++){
fscanf(Fdata,"%f %f %f %f \n", var_1, var_2, var_3, var_4); //skip the first 50 lines
}
fscanf(Fdata, "%f %f %f %f \n", var_1_10, var_2_10, var_3_10, var_4_10); //save the numbers on line 10
i = 10;
while ((var_2_10 - var_2)<0.05*(*var_2_10)){
fscanf(Fdata,"%f %f %f %f \n", var_1, var_2, var_3, var_4); //keep reading until var_2 is 5% lower than var_2_10
i++;
}
fprintf(Foutput, "%d \n", i); //print the number o the last line read
fclose(Foutput);
return 0;
}
Now, the script compiles, but when I try to execute it, it gives me the "segmentation fault (core dumped)" error. Does anyone know what I'm doing wrong? I have almost no knowledge of C, so there are probably a lot of mistakes in my code.
The input.dat file looks like this:
1.8125 0.944824 7.43362e-05 7.88432e-06
1.74121 0.918457 4.73094e-05 0.000127544
1.69922 0.897949 6.00231e-05 2.91268e-05
1.7334 0.905762 0.000317385 7.81227e-05
1.70898 0.899902 0.000243394 2.10955e-05
1.72559 0.903809 9.5074e-05 0.000149768
1.71387 0.899414 0.000166243 0.000185066
1.68359 0.89209 0.00018385 0.000303927
1.68359 0.88623 0.000219556 0.000178714
1.70508 0.894531 0.000488326 0.000411066
1.69336 0.880859 0.000139567 0.000568174
1.70605 0.89209 0.000196065 0.000167238
1.69043 0.882324 5.66663e-05 0.00017306
1.67578 0.881836 0.00014178 0.000137113
1.67969 0.876465 0.000261803 2.60709e-05
1.67773 0.879883 0.000250439 8.21055e-05
1.71191 0.879395 0.000311615 0.000118544
1.68652 0.879883 0.00023477 0.000101067
1.68262 0.890625 0.000310484 8.81731e-05
1.70898 0.890137 0.000591565 3.71699e-05
1.70312 0.89502 0.000248289 7.57763e-05
1.71875 0.903809 0.000555975 4.18079e-05
1.71289 0.901367 0.000265478 3.96961e-05
1.69434 0.892578 5.50881e-05 0.00085942
1.68945 0.880371 0.000153156 0.0011145
1.66504 0.868164 0.000155594 0.000752835
1.65039 0.853027 0.000255484 0.00133279
1.6748 0.862793 0.000207765 0.00148763
1.66406 0.850586 0.00043458 0.00064662
1.63086 0.84082 0.00124341 0.000331652
1.66113 0.848145 0.00141408 0.00108942
1.64746 0.845215 0.000985863 0.000169982
1.65039 0.855957 0.000606564 0.000577116
1.65527 0.853027 0.000982811 0.000660586
1.63086 0.841309 0.000670502 0.00120878
1.64746 0.84668 0.000579282 0.000597114
1.67871 0.850586 0.000324774 0.00139627
1.63574 0.82959 0.000331599 0.00224275
1.61719 0.828125 0.000564358 0.00185258
1.66504 0.845215 0.000896463 0.00230424
1.64062 0.832031 0.000774724 0.00195404
1.62793 0.835449 0.000624469 0.00127606
chux provided you with a clue in his comment above.
You correctly seem to realize that - for integer placeholders - fscanf() expects a pointer to an integer (i.e. its address).
The problem is that the pointers you pass are 'pointing' to random addresses in memory.
So fscanf() tries to de-reference invalid pointers when parsing.
This would cause the segmentation fault you refer to.
Instead of
float *var_1, *var_2, *var_3, *var_4; // etc..
use
float var_1, var_2, var_3, var_4; // etc.
and in your calls to fscanf() pass the address of these variables (not the variables themselves). E.g., instead of
fscanf(Fdata,"%f %f %f %f \n", var_1, var_2, var_3, var_4);
use
fscanf(Fdata,"%f %f %f %f \n", &var_1, &var_2, &var_3, &var_4);
You will need to make this change for all of your fscanf() calls.
There is one more issue with your program.
Once you declare var_1, var_2, etc. as floats rather than pointers to floats, you will need to change one other line in your code - involving a pointer dereference.
Since var_2_10 will no longer be a pointer, it will not make sense to de-reference it.
You might be able to resolve that yourself - the culprit line is reasonably obvious.
As an aside, variables with local scope - if not explicitly initialized - will contain random values. So your variables var_1, var_2, etc. will be pointing to random addresses.
The problem is with your fscanf(). you should use fscanf(Fdata,"%f %f %f %f \n", &var_1, &var_2, &var_3, &var_4);. If you are working with a file always check whether the file is loaded or not. Below there is code that helps you to check for loaded file and then do your task.Click here to get code

C program \n and while loop

guys I have a C program question. My goal is to make a change operation working for taking a price and giving out the current amount remaining. I code in java, so this is my first time in C, Im not looking to have my entire code done for me. I can do the code, however im having trouble getting it to execute the way I want. My problem here is that when I use \n my code seems to work, but my output is really weird, i have to add constant spaces and repeat my lines. not sure why this is happening, Also my while loop does not seem to execute, which is making no sense to me. If anyone could help , I would apprectiate it. Thank you for reading, ps I reply isntantly
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
/* Header comment that describes the purpose of the program
* Name Karanvir Dhillon
* Date Jan 12
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (void) {
double tendered;
double changeDue;
double price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
int toonoe=0;
int loonie=0;
int quarter=0;
int dime=0;
int nickle=0;
int penny=0;
/* Statements to be executed */
printf("Total purchase price and tendered amount\n");
scanf("%lf %lf ", &price, &tendered);
printf(" %lf and %lf is \n", tendered,price);
changeDue=tendered-price;
printf("%lf \n", changeDue);
if(tendered<price){
printf("Not enough money recieved as payment \n");
}
if(tendered==price){
printf("Exact payment, no change given \n");
}
if(tendered>price){
printf("%lf Amount to be paid is \n", changeDue);
}
while(changeDue!=0.00){
if(changeDue<=100.00){
changeDue=changeDue-100.00;
hundred=hundred+1;
}
if(changeDue<=20.00){
changeDue=changeDue-20.00;
twenty=twenty+1;
}
if(changeDue<=10){
changeDue=changeDue-10.00;
ten=ten+1;
}
if(changeDue<=5){
changeDue=changeDue-5.00;
five=five+1;
}
if(changeDue<=2){
changeDue=changeDue-2.00;
toonoe=toonoe+1;
}
if(changeDue<=1){
changeDue=changeDue-1.00;
loonie=loonie+1;
}
if(changeDue>1){
for(int i=0;i<changeDue;i++){
if(i==0.25&&changeDue>=0.25){
changeDue=changeDue-0.25;
quarter=quarter+1;
}
if(i==0.10&&changeDue>=0.10){
changeDue=changeDue-0.10;
dime=dime+1;
}
if(i==0.05&&changeDue>=0.05){
changeDue=changeDue-0.05;
nickle=nickle+1;
}
if(i==0.01&&changeDue<0.05){
changeDue=changeDue-0.01;
penny=penny+1;
}
}
}
}
if(hundred!=0){
printf("%d hundred$ bills given as change \n",hundred);
}
if(twenty!=0){
printf("%d twenty$ bills given as change \n",twenty);
}
if(ten!=0){
printf("%d ten$ bills given as change \n",ten);
}
if(five!=0){
printf("%d five$ bills given as change \n",five);
}
if(toonoe!=0){
printf("%d toonie coins given as change \n",toonoe);
}
if(loonie!=0){
printf("%d loonie coins given as change \n",loonie);
}
if(quarter!=0){
printf("%d quarter coins given as change \n",quarter);
}
if(dime!=0){
printf("%d dime coins given as change \n",dime);
}
if(nickle!=0){
printf("%d nicke coins given as change \n",nickle);
}
if(penny!=0){
printf("%d penny coins given as change \n",penny);
}
return 0;
}
In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.
Include a '\r' along with (or perhaps instead of) the '\n' in output strings. For example:
printf("Hello world\r\n");

C programming opening and reading from a file

int main(void){
FILE *ifp; //input file pointer
int totalClock; //total clock count
// BEGIN OPERATIONS=============================
ifp=fopen("prog1.asy.txt", "r");
system("PAUSE");
assert(ifp!=NULL);
//populate the instMem with inst===================
int i=0;
//system("PAUSE");
for (i=0;i<512;i++)
{
inst temp=parser(ifp);
if (temp.opcode==-1)
break;
instMem[i]=temp;
printf("%s\n", instMem[i].rawCode);
}
printf("\n%d instructions parsed\n", i-1);
system("PAUSE");// PAUSE TO CHECK CODE PARSING IS CORRECT========
int cont=0;
while (cont==0){
//begin sim================================================
//initialize the mem=======================================
int i;
for (i=0;i<512;i++)
data[i]=0;
for (i=0;i<32;i++)
reg[i]=0;
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
//prompt input parameters===================================
printf("Memory access time: c=");
scanf("%d", &c);
printf("\nMultiply time: m=");
scanf("%d", &m);
printf("\nExecute time: n=");
scanf("%d", &n);
assert(c>0);
assert(m>0);
assert(n>0);
//start execution now that the program has been broken to unparsed strings====
while (0==0)
{
WB();
MEM();
if (MEM_WB.instruction.opcode==HALT)
break;
EX();
ID();
IF();
totalClock++;
system("PAUSE");
}
//PRINT RESULTS=============================================
printf("Run again with new parameters? 0=yes");
scanf("%d", &cont);
}
fclose(ifp);
system("PAUSE");
return 0;
}
struct inst parser(FILE *ifp){
char str[100];
struct inst temp;
if (fgets(str, 100, ifp)==NULL) {
inst temp={"NULL", -1,0,0,0};
}
else {
inst temp={str, 0,0,0,0};
puts(str);
}
return temp;
}
I am trying to read in a test file so that i can parse it into strings for analysis later. It opens the test file but it doesn't read the lines of test in the code. Is there something I am doing wrong.
Your parser functions only reads once from the file and does nothing with the result (since temp would be a local variable to the if branch, not to the function). First thing is to remove inst from inst temp = ... to see that it reads the first instruction. Then, you need to make that function loop over all lines in the file.
First of all, you need to format your source code on this page to make it more readable.
For parser(), I don't think you can return a structure. So please use a pointer instead. And, as Mihai mentions, "temp" is a temporary variable located on the stack, and it will be destroyed when returning from function parser().
I don't see the declarations of variables in the code snippet:
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
So I assume you could remove some unused code to make the question clear.
The last thing is: to analyze log files, shell scripts is more suitable than C. If you're not working on a UNIX/Linux box, you could also use Perl/Python if you want. They are all less error prone and easy to debug when used to analyze log files.

My program crashes, and I don't understand why

I am coding a record-keeping program in C using binary file handling. I am using Code::Blocks, with gcc to compile my C program on Windows 8.
When the program reaches to the following block, an error-message appears:
My code:
int dispaly(student record[], int count)
{
/*
This is what structure `student` looks like:
int id;
char name[200], phone[20], address[200], cclass[50];
char sec[20], roll[50], guardian_name[200], relation[200] ;
char p2_colg[100], slc_school[200];
float plus2_percent, slc_percent;
struct date dob;
struct date enr_date;
struct date looks like
int day, month, year;
*/
printf("Reached"); /*Program Runs Fine upto here*/
int i = 0;
for(i=0; i<count; i++)
{
printf("\nId: %d\tPhone: %s\nName: %s\nAddress: %s"
"\nClass: %s\tSection: %s\nRoll: %s\nGuardian Name: %s\tRelation:%s"
"\nPlus-Two in: %s\tPercentage:%f\nSLC School: %s\tPercentage: %f"
"\nDate Of Birth(mm/dd/yyyy): %d/%d/%d"
"\nEnrolled in (mm/dd/yyyy): %d/%d/%d\n\n---------------------------------------\n", record[i].id, record[i].name, record[i].address
, record[i].cclass, record[i].sec, record[i].roll, record[i].guardian_name, record[i].relation, record[i].p2_colg
, record[i].plus2_percent, record[i].slc_school, record[i].slc_percent, record[i].dob.month, record[i].dob.day, record[i].dob.year
, record[i].enr_date.month, record[i].enr_date.day, record[i].enr_date.year);
}
getch();
return 0;
}
The program compiles without any errors or warnings.
What's going on?
Hard to tell exactly what crashed without looking at the exact data in your array, but you forgot "phone" in the arguments list to printf, which could certainly result in a crash inside printf.
There's not a terribly good reason to stack those all up into one call. It would have been easier to spot your bug of the missing "phone" if you separated each line out into its own printf. Also, you could cut down on the redundancy if you captured record[i] into a pointer.
Contrast with:
student * r = &record[i];
printf("\n");
printf("Id: %d\tPhone: %s\n", r->id, r->phone);
printf("Name: %s\n", r->name);
printf("Address: %s\n", r->address);
printf("Class: %s\tSection: %s\n", r->cclass, r->sec);
printf("Roll: %s\n", r->roll);
printf("Guardian Name: %s\tRelation:%s\n", r->guardian_name, r->relation);
printf("Plus-Two in: %s\tPercentage:%f\n", r->p2_colg, r->plus2_percent);
printf("SLC School: %s\tPercentage: %f\n", r->slc_school, r->slc_percent);
printf("Date Of Birth(mm/dd/yyyy): %d/%d/%d\n",
r->dob.month, r->dob.day, r->dob.year);
printf("Enrolled in (mm/dd/yyyy): %d/%d/%d\n"
r->enr_date.month, r->enr_date.day, r->enr_date.year);
printf("\n");
printf("---------------------------------------\n");
In a technical sense, making multiple calls to printf will incur some function call overhead. And declaring a pointer variable for the current student in the array will incur some storage space. But it is basically negligible, and of no consequence in a case like this. Under the hood, the output is buffered anyway.

Resources