I keep running in to this issue when trying to read any data from a file (the files first line does contain a number). To do this I used
fscanf(Read_File, "%d", &Number);
This is my full code
#include <stdio.h>
#include <string.h>
int main (void)
{
char Name[50] = "Test";
int Number = 5;
FILE* Read_File;
Read_File = fopen("Employee Details.txt", "r");
fscanf(Read_File, "%d", &Number);
printf("%d", Number);
//puts(Name);
}
Each time I try and run this though I get the error in the image bellow.
Image Or Error EXC_BAD_ACCESS
This is something that I have done before when using Visual Studio but that dosent seem to be available for Mac, and since I switched recently Xcode seems to be my best bet.
2
Answers
Your code seems to be fine per testing on my side. It is highly likely that your program does not find your file during run time — hence throwing the EXC_BAD_ACCESS exception — because the code tries to read from a stream that is actually not available to the program.
Here is your code, adjusted to 1.) only attempt file read if the file is found and opened, and 2.) alert the user if the file failed to open.
The default assumption for this sort of crash is a memory management error. In this case, it seems that the program was unable to find the file, which resulted in
fopen()
returning a null pointer, which was later passed tofscanf()
, and hence undefined behaviour was invoked. Consider:Also consider checking the return value of
fscanf()
.