I ran the following test after trying to help someone with a piece of Python code; I know the test is simple but I can't figure out why this happens.
The basic idea is this: I have the following C code:
#include <stdlib.h>
#include <stdio.h>
int main() {
FILE *pf = fopen("test.txt", "r+");
char buf[100];
fgets(buf, 100, pf);
fseek(pf, -7, SEEK_CUR);
fwrite("0", 1, 1, pf);
//NEXT LINE PROBLEMATIC
fgets(buf, 100, pf);
fclose(pf);
return 0;
}
and the input file containing one line: abcdefghijklmnopqrstuvwxyz
I would expect the output to contain a zero inside the string; however, this happens: abcdefghijklmnopqrs0bcdefghijklmnopqrstuvwxyz
(there are multiple space characters after the text). If I comment out the problematic line (the second call to fgets), the output works as expected.
Does anybody have any idea why that happens?
To me it seemed like a buffer overflow because of the space characters after the end of the line; reproducing using cl.exe instead of gcc I get this: abcdefghijklmnopqrs0bcdefghijklmnopqrstuvwxyzt e s t e \ p y _ w e i r d \ t e s t . t x t c l e ;i À ] h&^ u a
So it's definitely an overflow caused, most likely, by interweaving calls to fgets with calls to fseek/fwrite.