tags:

views:

44

answers:

2

I've got a C program that encounters errors when I enter a while loop.

I initialize a variable (fragmentcount) and write into it using fscanf and assign it a value of 4 (this works)

int fragmentCount;
if ((fscanf(fp, "%i", &fragmentCount)) == 1) {
   ...
}

However, when I try to access it in a while loop below, fragmentCount = 0

while ((fscanf(fp, "%[#]", discards)) != EOF) {
   printf(fragmentCount); // <- pseudocode
}

For a brief experiment, I tried taking away the fscanf as the conditional test for the while loop, and fragmentCount was the correct value (4).

Why is this so? How can I avoid this?

A: 

fscanf reads a value from a file and interprets it according to the format string. The '%i' format string is unknown (perhaps you meant '%d'?) according to http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/, so you are unlikely to read the value you expect.

Apart from file FILE* and the format string, all parameters to fscanf are out parameters, which means the value they contain before the call to fscanf are irrelevant and could be replaced.

Zooba
%i is integer format - it allows octal, hex, or decimal. http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html
David Gelhar
Ah, I understand the question better now. You're right, a buffer overflow is much more likely.
Zooba
+1  A: 

How is discards declared? It is possible that fscanf is reading more data than discards has room for, which might overwrite the value of other variables.

Using the '%[' format without a field width is a bad idea - it leaves your program open to buffer overflow errors.

David Gelhar
char discards[2];
Daniel
@Daniel that will be trouble if there's more than one consecutive '#' - you only have room for 1 (plus the terminating nul).
David Gelhar
There's only one # (thus the 2), but By stepping through GDB, it is this line that kills everything: fscanf(fp, "%[#]", discards);
Daniel
OH you're right. My test file had an extra #! Argh!
Daniel
Props to you- saved my night :)
Daniel
and **that** is why you never do an unbounded '%[' format - can't trust those pesky users not to give you bad input :-)
David Gelhar