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.
Related
I'm working on 64-bit Xubuntu 14.04.
I have a fairly large C program and to test new features, I usually implement them in a separate program to iron out any bugs and whatnot before incorporating them into the main program.
I have a function that takes a const char* as argument, to indicate the path of a file (/dev/rx.bin in this case). It opens the file, reads a specific number of bytes into an array and then does some things before exporting the new data to a different file.
First off I allocate the array:
int16_t samples = (int16_t *)calloc(rx_length, 2 * sizeof(samples[0]));
Note that rx_length is for example 100 samples (closer to 100 000 in the actual program), and it's calculated from the same constants.
Next I open the file and read from it:
uint32_t num_samples_read;
FILE *in_file = fopen(file, "rb");
if (in_file == NULL){
ferror(in_file);
return 1;
}
num_samples_read = fread(samples, 2 * sizeof(samples[0]), rx_length, in_file);
Here's the kicker; the return value from fread is not the same between the test program and the main program, while the code is identical. For example, when I should be reading 100 000 samples from a 400 kB file (100 000 samples, one int16_t for the real part and one int16_t for the imaginary part, adds up to four bytes per sample), the value returned is 99328 in the main program. For the life of me I cannot figure out why.
I've tested the output of every single variable used in any calculation, and up until fread() everything is identical.
I should also note that the function is in a separate header in my main program, but I figured that since printing every constant / definition gives the expected result, that it's not there where I'm making a mistake.
If there's anything that I might have missed, any input would be greatly appreciated.
Regards.
Thank you chux for reminding me to close and answer.
Closing the file was the problem in my main program, it never occurred within the test environment because the input file was not being modified there.
Once the RX thread has completed its task, make a call to fclose():
rx_task_out:
fclose(p->out_file);
// close device
// free sample buffer
return NULL;
Previously, only an error status with creating the RX thread caused it to close the file.
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.
I have this program for class where we just need to show that we can read, write and populate an array from both a text and binary file. I didnt have many issued with the binary file but the text file is giving big time brain pains.
I believe this little bit of code is to blame. userInputText[MAXSIZE]is a char array (MAXSIZE is defined at 100000) and both textCount and textCounter are initialized to zero when the program is at this point.
textPointer = fopen("textFile.txt", "r");
if (textPointer)
{
while (fgets(userInputText, sizeof(userInputText), textPointer) != NULL)
{
sscanf(userInputText, "%d", &textCount);
userInputText[textCounter] = textCount;
textCounter += 1;
}
}
When the user first runs the program, this part of the program is skipped and the user is asked to create and write to a text file. The user inputs integers and they are written to a text file and stored in userInputText and displayed to the screen at the end of the program. All of that works fine, the text file is appended correctly every time the program runs. I have tried about every combo I can think of in the above piece of code. I have tried using fopen(r+), sizeof(int and MAXSIZE), experimenting with the %d. In my fprintf part later in the program I have "\n" set as a delimeter, but I have also tried removing it. I switched out the fgets for fread. Ive gotten to the point where I'm resembling a baboon throwing poo at the problem.
I don't want people to think I am lazy and looking for an easy answer, mentally handicapped maybe but not lazy.
Any suggestions?
Thanks,
Mike
Try while( !feof(textPointer) )
{ fgets(userInputText,MAXSIZE,textPointer); }
sizeof(userInputText) will only return the size of a char pointer.
I am trying to parse a given textfile, but so far, my program does not seem to be reading properly.
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fr; //file pointer
int buildingFloors = 1;
printf("sanity check\n");
fr = fopen (argv[0], "r");
fscanf(fr, "%d", &buildingFloors );
printf("%d\n", buildingFloors);
fclose(fr);
return 0;
}
I compile the program and run it on my redhat linux machine with the following command:
./sjf file.text
file.text is a text document with a "4" as the first character. So I would expect my output to be
sanity check
4
However, when I run my program I instead get
sanity check
1
Which implies that fscanf didn't properly read in the first character -- 4. Do I have some syntax error that's preventing the expected code functionality? Am I supposed to scanf for a character, and then convert that to an int somehow?
argv[0] is the name of the program (./sjf in your case), so you're trying to read in your own program's executable. Use argv[1] instead to get the first real program argument.
One thing which immediatly comes to mind is that the program args include the executable name as the first element
argv[0] is "sjf"
argv[1] is "file.text"
so you should be using
fr = fopen (argv[1], "r");
Remember when debugging to always try and narrow the problem down, if you know the location of the error the cause often becomes obvious or at least investigatable.
In this case you should check argc >= 2, print out argv[1] to ensure you are trying to open the right file, then also check that the file was opened successfully.
Finally check the fscanf error codes to see that fscanf was able to read the number.
Your code looks clear and straight-forward, but there is one important thing missing: error handling.
What happens if the file you want to open does not exist? fopen returns NULL in that case.
What happens if the file does not start with a number? fscanf returns the number of fields that have been successfully read, so you should check that the return value is at least 1.
You need to somehow handle these cases, probably by printing some error message and exiting the program. When you do that, be sure to include the relevant information in the error messages. Then you will find the bug that the other answers have already mentioned.
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.