Unhandled Exception Error C Programming - c

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.

Related

Can someone help me determine the cause of my Seg Fault in C and the meaning of the gdb output?

When I run the program it prints out "SUCCESS!!!!" if it works alright, but I keep getting seg faults and I can't seem to figure out where. Can someone help me determine what exactly causes the signal SIGABRT and what is the most likely cause of why getting segmentation faults?
My code is written in c.
EDIT:
In my main code on line 97 I have the function fclose(fp) but I should have already read through it in another function. Here is my code from main.c:
FILE *fp = NULL;
if(fp = fopen(full_filename, "r")){
Node* tree = NULL;
tree = parser(fp);
printTree(tree, 1);
fclose(fp);
}
else
printf("Error file DNE\n");
return 0;
The function parser gets the file pointer and sends that file pointer to another function called scanner. Then scanner creates a list of words from that file. Then parser checks grammar of the words.
EDIT 2:
I got rid of fclose(fp) in main and when I ran it in gdb, I got no errors. But when I ran it without gdb I still get a seg fault.
There isn't too much information, but looking at the trace it would be my guess that you are trying to close a file with fclose() or iofclose(), and the file may not exist, or it is not open.
Conclusion
The problem must lie in your parser() function. It seems it is altering your file pointer and making it invalid.
Explanation
I state this because I it can't enter your if(fp = fopen(full_filename, "r")) statement unless the pointer is valid, but when you try to close it, the pointer seems to be invalid.
Note that
The only line which is able to affect your pointer is the one showing the folowing:
tree = parser(fp);

Segmentation fault when reading a binary file into a structure

I'm experiencing some problems while trying to read a binary file in C.
This problem never happened to me before, I don't really know how to manage it.
So, there's this structure called "hash_record", there are many of them stored in my "HASH_FILE" file in binary mode. This is the structure:
typedef struct hash_record {
char *hash;
char *filename;
} hash_record;
I write the file in this way:
hash_record hrec;
[...] code that fill the structure's fields [...]
FILE* hash_file = fopen(HASH_FILE, "ab");
fwrite(&hrec, sizeof(hash_record), 1, hash_file);
fclose(shared_file);
This is just a summary, the fwrite() function is inside a loop so that I can fill the file with many hash_record's.
Then, immediately after that piece of code, I start reading the file and printing some data to be sure everything went well. This is the code:
int print_data() {
hash_record rec;
printf("Data:\n");
FILE* hash_file = fopen("hash.bin", "rb");
if (hash_file == NULL)
return -1;
while(fread(&rec, sizeof(hash_record), 1, hash_file) == 1)
printf("Filename: %s - Hash: %s", rec.filename, rec.hash);
fclose(hash_file);
return 0;
}
And everything works just fine!
The problem is that if I write the binary file in an instance of my program and then quit it, when I open it again (commenting the code which write the file so it can only read it) it gives me a Segmentation Fault. This error appears when I call the printf() inside the while() loop. If I just print a common string without calling "rec" no errors are given, so I'm assuming there's something wrong storing data inside "rec".
Any idea?
Thank you!
You are writing out pointers. When you read them back in from the same instance of the program, the data is in the same place and the pointers are meaningful. If you read them in from another instance, the pointers are bad.

Debug assertion failed . while using fscanf

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.

problem with fprintf

I am running a simulation in C, and need to store 3 100x100 matrices ~1000 times. My program runs just fine when I'm not writing the data to file. But when I run my program and write the data, I get a segmentation error after 250 time steps or so. And I don't understand why.
My save function looks like this
void saveData(Simulation* sim, int number) {
sprintf(pathname_vx, "data/xvel%d.dat", number);
sprintf(pathname_vy, "data/yvel%d.dat", number);
sprintf(pathname_rho, "data/rho%d.dat", number);
FILE* vx_File = fopen(pathname_vx, "w");
FILE* vy_File = fopen(pathname_vy, "w");
FILE* rho_File = fopen(pathname_rho, "w");
int iX, iY;
double ux, uy, rho;
for (iY=0; iY<sim->ly; ++iY) {
for (iX=0; iX<sim->lx; ++iX) {
computeMacros(sim->lattice[iX][iY].fPop, &rho, &ux, &uy);
fprintf(vx_File, "%f ", ux);
fprintf(vy_File, "%f ", uy);
fprintf(rho_File, "%f ", rho);
}
fprintf(vx_File, "\n");
fprintf(vy_File, "\n");
fprintf(rho_File, "\n");
}
fclose(vx_File);
fclose(vx_File);
fclose(vy_File);
}
where 'Simulation' is a struct containing a lattice (100x100 matrix) with 3 different variables 'rho', 'ux', 'uy'. The 'number' argument is just a counting variable to name the files correctly.
gdb says the following, but it doesn't help me much.
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000010
0x00007fff87c6ebec in __vfprintf ()
I'm not that experienced in programing, so I guess there are better ways to write data to file. Any attempt to clarify why my approach doesn't work is highly appreciated.
Thanks
jon
Looks like you're closing vx_File twice, and not closing rho_File at all. This means that you're leaving rho_File open each iteration, and thus using up a file descriptor each time through.
I'd guess the program fails you're running out of file descriptors. (Since this happens on the 250'th iteration, I'd guess your limit is 256). Once you're out of file descriptors, one of the fopen() calls will return NULL. Since you don't check the return value of fopen(), the crash will occur when you attempt to fwrite to a NULL handle.
Looks like a NULL pointer dereference. You need to check the result of fopen() to make sure it succeeded (non-NULL result).
Maybe you run out of memory when you are creating those thousand 100x100 matrices (or whatever is exactly happening). You could then end up with a incomplete sim->lattice that might contain NULL pointers.
Do you check if you malloc() calls succeed? If they can't allocate memory they return NULL.

determining segmentation fault occurring in loop? [closed]

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.

Resources