Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
On running the following script, I get segmentation fault. The output consists of "here 5a". But nothing beyond it. Any suggestions on what might be going wrong?
if(model==1)
fptr3=fopen("poisson.pro","r");
if(model==2)
fptr3=fopen("jtt.pro","r");
if(model==3)
fptr3=fopen("estimate.pro","r");
printf ("here 5a\n");
for (i=0;i<20;i++)
fscanf(fptr3,"%lf", &freq[i]);
printf ("here 5ai\n");
for (i=0;i<20;i++)
{
printf ("here 5b\n");
for (j=0;j<20;j++)
{
printf ("here 5c\n");
fscanf(fptr3,"%lf", &prob[i][j]);
if(model==3)
prob[i][j]=prob[i][j]/10000.0;
}
}
UPDATE
double freq[20], prob[20][20];
Are you sure this code is called and "model" is either 1, 2, or 3? If not, fptr3 would not be set, so if you try to do anything with it you'd be in trouble.
Try this instead?:
void modeltest (int model)
{
FILE *fptr3 = NULL;
int i = 0;
int j = 0;
double freq[20], prob[20][20];
if(model==1) fptr3=fopen("poisson.pro","r");
if(model==2) fptr3=fopen("jtt.pro","r");
if(model==3) fptr3=fopen("estimate.pro","r");
printf ("here 5a\n");
if (fptr3 != NULL) {
for (i=0;i<20;i++) fscanf(fptr3,"%lf", &freq[i]);
printf ("here 5ai\n");
for (i=0;i<20;i++) {
printf ("here 5b\n");
for (j=0;j<20;j++) {
printf ("here 5c\n");
fscanf(fptr3,"%lf", &prob[i][j]);
if(model==3) prob[i][j]=prob[i][j]/10000.0;
}
}
}
else {
printf ("fptr3 is NULL!\n");
}
}
An additonal note. Please, please, please consider consistent brace styles! :)
Is this C# ???? wooow no kidding you are getting segfaults...
Do you know what return codes are for ???
You really need to improve your code before asking for this kind of help....this is really unreadable, and ugly code...
Start adding some check to your file pointers
if(1==model)
{
fptr3=fopen("poisson.pro","r");
if(null == fptr3)
{
perror("Fopen failed");
}
...
valgrind is the sovereign remedy for segfaults in C. It finds errors before the segfault and tells you exactly what you did wrong. For maximum benefit, compile with debugging symbols turned on.
I agree with Daniel, you need to be checking your return values and pointers.
I also agree that you need to do a better job blocking and formatting your code. Supposing that you are the only one that ever reads it, in a couple of weeks even you will have forgotten enough that you won't be able to follow it.
Towards Matthews point, you could try deleting everything starting with the line:
printf ("here 5ai\n");
Of course, only bother with this after checking the file pointer.
Another crazy idea would be stepping through it with a debugger. I know it's hard to use a debugger when you have such great debugging options as the printf statement, but sometimes a debugger can be a huge time saver (for example, when you keep getting segfault). Also, learning how to use the debugger for the platform you are developing on is one of the things that separates good coders from the pack of average hacks. (FYI, you could even try looking at your core in the debugger and maybe see exactly where the problem is. (Hint: if you don't have a core file try 'man ulimit'.))
If you are going to insist on using printf as your only means of debug, then call flush right after each use.
What's freq defined as? What's prob defined as?
Is the first for loop meant to only run fscanf for freq? Or is it supposed to encompass the entire block?
EDIT: Rationale - If all you see is 5a, then it's faulting in the fscanf on freq. You may have allocated too little space for freq, or used an incorrect type.
Check the return code and print if needed the error code of your files with perror() (see. daniel answer). Calling fscanf() with a FILE * to NULL, will surely do a segfault.
As you specified %lf, freq must be an array of at least 20 doubles, not just float.
See man ffrintf().
use a debugger instead of printf().
You should post the contents of the beginning of whatever file is getting opened since it's crashing in fscanf. Either the file doesn't exist, or it's malformed when stacked against to how you are trying to parse it.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
#include<stdio.h>
void main()
{
FILE *a[10];
int i,j,k;
float b[10][4][4];
for(i=0;i<8;i++)
{
char filename[100];
sprintf(filename,"infile%d.txt",i);
a[i]=fopen(filename,"r");
}
for(i=0;i<8;i++)
{
for(j=0;j<2;j++)
{
for (k=0;k<3;k++)
{
fscanf(a[i],"%f",&b[i][j][k]);
}
}
}
for (i=0;i<8;i++)
{
printf("\n-----------------%d--------------------",i);
for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
{
printf("\nb[%d][%d][%d]=%f",i,j,k,b[i][j][k]);
}
}
}
}
I have written the above code in C. Which just reads 8 different files and print it in terminal. The file name is infile0, infile1 and son on up to infile7. Though the code runs, it shows segmentation fault core dumped in the terminal. I couldn't figure out why this happens at all. Can some one help me figure out the mistake in the code.
Compiling with -g and running trough valgrind gives an error line 19 when no files are present.
Maybe you should add
if(!a[i])continue;
before scanf. (and set some message or default values).
also have a look at Input validation using scanf(), as you should check scanf return value.
I hope it helps, this my my first so contribution.
EDIT:
the -g flag is for your compiler, e.g
gcc -g myfile.c -o myfile
then run your binary trough valgrind.
It will tell you any problems with memory: leaks, invalid red/write...
valgrind ./myfile
Don't forget to install valgrind if it is not on your system.
A lot of remarks can be done from your code
1) In
void main()
main returns an int, not void, so must be
int main()
2) In
FILE *a[10];
..
for(i=0;i<8;i++)
{
...
a[i]=fopen(filename,"r");
why do you have an array with 10 entries to only use 8 of them ?, better to have
FILE *a[8];
3) 10 (becoming 8) is used a lot of times in your code, if you decide to change the number of elements you will have to change it every where, it is more simple to use a #define or sizeof(a)/sizeof(a[0])
4) In
char filename[100];
sprintf(filename,"infile%d.txt",i);
you are very generous with the needed size, even your int are in 64b and you increase so much the number of entries in a (no change to have enough stack nor file description anyway) 20 digits are enough for a positive number, so char filename[20+10+1]; is enough
5) In
float b[10][4][4];
...
for(j=0;j<2;j++)
{
for (k=0;k<3;k++)
like for 2) there is no reason to use a so large array if you do not use all the entries
6) In
fscanf(a[i],"%f",&b[i][j][k]);
you do not check if the corresponding file was open so if a[i] is not NULL, probably your segmentation fault comes because a file wasn't open
you do not detect the end of file nor if the file doesn't contain a valid float, you need to do for instance if (fscanf(a[i],"%f",&b[i][j][k]) != 1) { ...error management... }
I'm a novice programmer, with probably about 8-9 weeks experience of C programming.
Currently I am working on creating a program that will read some lines from a text file, store them in a structure, calculating a couple things, then print the data out. I am using Microsoft Visual 2010 Express
Whenever I try to run the program, it immediately gives me an error message:
Unhandled exception at 0x777915de in Lab 7 Part B.exe: 0xC0000005:
Access violation reading location 0x00460310.
My question - is there anything I can do to track down where this problem is originating?
I'm not 100% sure if I am allowed to post my entire code onto here, as that may be considered being a slacker and not figuring things out myself. Since I also have no idea where it's coming from, I can't post a specific block of my code either. Sorry.
If I try to run it once more it comes up to this error:
Unhandled exception at 0x777915de in Lab 7 Part B.exe: 0xC0000005: The
operation completed successfully.
Then it just stays there whenever I try to run the program several more times. Both errors ask for me to either 'Break' or 'Continue'.
If its any help, the second error consistently stops at this line of code.
SetLastError(TL_LastError);
return(ptd);
With the green arrow pointing at the return. The file the accompanies the error is called 'tidtable.c'. If I am able to uncover anything to help solve this, I will update this ASAP.
Thanks.
EDIT:
So I found out about F10 and eventually just worked through the code, and somehow found that the error is coming up when the yellow arrow points at the getdata line. Then when I press F10 once more, the error begins and stays there. I posted the blocks of code that I think are the culprits and hopefully will solve the problem.
Here is my main function:
void main()
{
SCARADATA data;
getdata(&data);
}
Here is the function:
void getdata (SCARADATA *data)
{
int i;
FILE *file;
char fName [MAX];
sprintf (fName, "(exactfilepath)");
file = fopen(fName, "r");
if(file==NULL)
{
printf("\nInvalid File.");
system ("pause");
}
else
{
for (i=0; i<=10; i++)
{
fscanf (file, "%s\t%lf\t%lf\t%d", data[i]->stringname, data[i]->x, data[i]->y, data[i]->elbow);
}
}
fclose (file);
}
Here is the structure I am using to store the data read:
typedef struct
{
char stringname[40];
double x, y;
int elbow;
double ang1, ang2;
bool isValid;
} SCARADATA [20];
And a sample of what the program is reading of the text file. There are 10 lines of this. (pt1 - pt10)
pt1 -400 400 1
EDIT 2:
With fizzer's help, we have fixed the program. From his explanation, I was sending the address of the array of 20 structures into my getdata function, which is the same as the address for the first structure of the 20. What I did to fix the problem was added a for loop around the call of the functions to cycle through the address of each structure.
for (i=0; i<10; i++)
{
getdata(&data[i]);
findangles (&data[i]);
printdata (&data[i]);
}
This allows the program to pass the address of EACH structure into the following functions, instead of passing the entire array's address. The unhandled exception error, from what I gathered through is caused by the program not being able to store the information within the file into the array. This caused the compiler to then read garbage, resulting in an error each time the file is opened to gather data. At least, I think that's what happened.
Thanks for your help fizzer! Definitely saved me a couple nights staring at this code.
&data[i]->x, &data[i]->y, &data[i]->elbow
scanf needs pointers. (data[i]->stringname is already a pointer to the first element).
Edit
What is SCARADATA supposed to be? The type of the whole array of 20 structs, or the type of one element in the array? I suspect the latter. Here's one way to make your program run:
typedef struct
{
...
} SCARADATA; /* not [20] */
/* . instead of -> */
fscanf (file, "%s\t%lf\t%lf\t%d", data[i].stringname, &data[i].x, &data[i].y, &data[i].elbow);
int main() /* main returns int */
{
SCARADATA data[20];
getdata(data);
return 0;
}
See the comp.lang.c FAQ for details of arrays versus pointers.
First, please note that C has no exceptions in the sense of C++, Java etc.
This "access violation" seems to be what in some other operating systems is referred to as a "segmentation fault" : you are accessing memory that you should not, because of improper use of pointers (or arrays, which are the same in C).
Advice : run this program in a debugger.
Hey I've tried a lot of programs in Visual Studio and in most of them when i try taking the input from a stream ( while using fscanf ) it invariably throws a debug assertion failed error ..
and goes on to say:
stream != NULL. Since I have gotten this error a number of times .. I assume there is a flaw in the way I'm using fscanf. I would appreciate it if someone could tell me the usage or .. give me a demo sample code that illustrates the simple usage .. !
I tried looking up the error .. in most places it said I haven't closed the file .. but I have and I'm a little confused .. I appreciate any help .. thanks a lot :)
printf("Enter No of states\n");
Q=5;
// scanf("%d",&Q);
// READING ZERO MATRIX
// reading the matrix from f0.sta
{
FILE *fp;
fp = fopen("c:\\tc\\fuzzy\\f0.sta","r");
for(i=1;i<=Q;i++)
for(j=1;j<=Q;j++)
fscanf(fp,"%f",&a0[i][j]);
fclose(fp);
}
// READING ONE MATRIX
// reading the matrix from f0.sta
FILE *fp;
fp = fopen("c:\\tc\\fuzzy\\f1.sta","r");
for(i=1;i<=Q;i++)
for(j=1;j<=Q;j++)
fscanf(fp,"%f",&a1[i][j]);
fclose(fp);
This is the code bit.
It sounds like fp is NULL. The most likely reason is that one of the files (or both) do not exist, or can't be opened (for example, because some other process is using it).
I would start by adding some error checking after the two fopen() calls: compare the result to NULL and if it is NULL, examine errno.
Your loop counters start at 1 instead of 0, which is odd for C programming. What's likely happening is you're not allocating enough space in the array, i.e. you have
double a[5][5];
when you need
double a[6][6];
so you're stepping on something past the end of the array. Better to have your loop be
for(i=0;i<Q;i++)
for(j=0;j<Q;j++)
so you don't waste the 0 slots in the array.
EDIT: About to try intilizing my chars properly... [didnt work=( ]
EDIT: SOLVED (I can't answer my own question for another 7 hours...)
Thanks for the comment Brian, that's just a constant declared at the top.. (it = 20).
It turns out the error was happening because I forgot to add a next line after I took in the input name.
it's working now =D
:ENDEDIT (lol)
I've code my code below, Basically I put in the first name this is supposed to find
John
Then I put in the last name...
Locke
and as soon as I enter in "Locke" it hits this error, I feel like maybe it's the scanf and I should be using a better alternative ???
int findPatron(struct Library *lib,struct Patron **p)
{
int i;
char firstName[NAME_LENGTH], lastName[NAME_LENGTH];
printf("\nPlease enter the patron's first name: ");
scanf("%s",firstName);
printf("\nPlease enter the patron's last name: "); //this line prints...
scanf("%s",lastName); //SEGMENTATION ERROR happens here I'm pretty sure.
printf("deerrrr"); //this line never prints
for(i = 0; i<lib->totalPatrons;i++)
{
printf("checking %s %s to %s %s",lib->patrons[i].name.first,lib->patrons[i].name.last,firstName,lastName);
if((strcmp(lib->patrons[i].name.first, firstName) == 0) && (strcmp(lib->patrons[i].name.last, lastName) == 0))
{
**p = lib->patrons[i];
return 0;
break;
}
}
return 1; //No Match!
}
You're getting the segmentation fault after your scanf() statements.
If you remove everything after printf("deerrrr"); and add a \n to that output so the buffer is flushed, you'll find that it all works just fine (provided NAME_LENGTH is at least 6 given your example input).
Part of programming is knowing how to isolate and debug your problems.
Your issues are with your loop and lib struct - you're dereferencing something you shouldn't be.
SEGMENTATION ERROR happens here I'm pretty sure
this line never prints
C's printf is buffered, and only gets flushed by an explicit call to fflush or a blocking action (like scanf, which AFAIK flushes stdout as well), so the error could happen in another place. Learn to use debugger, that's the proper way of debugging C programs.
I have a piece of C code where I try to write a buffer into an opened output file.I am getting a segmentation fault when I try to run the code.
if (fwrite(header, record_size, 1, uOutfile) != 1)
{
return 0;
}
The header is a properly populated and I am able to print out the contents of the header.the size of the buffer header is definitely greater than the record_size.Is there anything else worth checking.?Any other reason where fwrite can cause a segfault.Gdbing the problem gave the following output
0x00007ffff6b7d66d in _IO_fwrite (buf=0x726d60, size=16, count=1, fp=0x738820) at iofwrite.c:43
43 iofwrite.c: No such file or directory.
in iofwrite.c
it seems to suggest that the output file has not been created.how ever and ls -l on my directory shows the output file of size 0 bytes.
I would greatly appreciate if someone could throw some light on the problem.
EDIT: Code that opens the file:
outfd = open(out, O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0664);
if (outfd == -1) {
dagutil_panic("Could not open %s for writing.\n", out);
}
uOutfile = fdopen(outfd, "w");
I don't think there's enough here to know for sure what your problems are, but here are some thoughts:
Show us the code involving your FILE * (uOutFile) and your buffer (header) — we can then see if you're borking memory somewhere between.
Run your code through valgrind: You're getting a segfault, so it could probably catch what you're doing wrong.
In gdb, examine the contents of both header and uOutFile (not just the pointer, but the pointed-to-memory.) (You'll have to use some smarts to figure out if uOutFile looks right, but you should be able to up-or-down determine if header is correct.)
To add to this: my general debug strategy when I get segfaults is:
gdb's backtrace. Tells me where the segfault happened. Usually, this is enough to uncover the dumb thing I did.
Look at the pointers in the vincinity of the crash. Is the pointer correct, and is the pointed-to data correct? (esp. if you see something strange like 0xdeadbeef)
Valgrind Valgrind Valgrind
(2 & 3 are in no particular order.)