It’s been a very long time since I coded in C, and I’ve spent about two hours googling how to properly use fscanf. As far as I can tell, this code is correct, but I’m getting EXC_BAD_ACCESS every time I run it:
int rasterWidth;
int rasterHeight;
FILE* f = fopen("scene.u2d","r");
if (f == NULL)
{
perror("Can't open file!");
}
char m [2];
fscanf(f, "%s", m);
fscanf(f, "%d %d",&rasterWidth,&rasterHeight); // Getting EXC_BAD_ACCESS here
printf("%s %d %d",m,rasterWidth,rasterHeight);
I’ve verified that XCode is opening the proper file (it loads the first two chars correctly). scene.u2d looks like this:
U2
500 500
-1.0 -1.0 1.0 1.0
g triangle.raw
c 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1
s 0.5 1.0
t 0.3 -0.2
Is there something obvious that I’m doing wrong? Thanks!
First, the man page for
scanfsays:This means you need at least
char m[3]for that input file because of the null terminator.I would also recommend using
%2sas your format specifier so you don’t overflow the buffer.If that’s not the problem, have you tried running only the code snippet you posted? It works for me – I suspect there’s some memory mismanagement before the posted code. Or, is your code actually something like:
Bad accesses are on scanf calls are often caused by passing uninitialised pointers in.