I am reading a plain text from a file – by lines, with a following function:
int readline(FILE *in, char * buf) {
char c;
buf[0]='\0';
for (int i=0; i<BUFSIZ-1; i++) {
fread(&c,1,1,in);
if (ferror(in)) return 1;
if (feof(in)) break;
buf[i]=c;
if (c=='\n') break;
}
if (buf[BUFSIZ-1]!='\0') return 1;
return 0;
}
It reads correctly 28816 characters, and then the trouble starts.
Instead of reading the next four characters:
' ' 'f' 'o' 'r'
it reads the weird thing:
'\x01' '\0' '\0' '\0'
After that, it reads everything correctly until 33080 character.
Instead of reading next 12 characters correctly, it reads three sequences:
'\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0'
Then, it reads everything correctly again, until certain point.
There weren’t neither (ferror(in)) nor (feof(in)) condition true when this problem occurs.
Do you have any ideas about the cause of this problem?
It doesn’t look like random data – it is the byte sequence for an integer value of 1 (assuming x86 or similar CPU).
I would expect one of two situations:
1) you’re writing off the end of the buffer, and something else is using the same memory
2) somewhere else in your program, you’re writing off the end of another array into the memory used by the buffer.
From the comments, I see you’ve debugged it, seemingly ruling out both options. I wonder whether optimisation was disabled when you were debugging? I’ve had tricky experiences debugging an optimised binary in the past.