0

Codeblocks, C. I'm trying to write characters to a .txt file, using fwrite. The first couple of characters get written correctly, but after them the file says: _mcleanup: tos ov. I think it might be a buffer overload. Any ideas?

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    FILE*p1;

    p1=fopen("Tomi.txt","w+");

    fseek(p1,0,SEEK_SET);

   // fwrite("Toth Tamas",sizeof(char),30,p1);

    while(a<10)
        {
            fwrite("Toth Tamas",sizeof("Toth Tamas"),1,p1);

            a++;

        }

    return 0;
}
  • I've put the code in the discription. I tried it with while, and with only fwrite as well. – Thomas Tóth Sep 24 '13 at 21:27
  • This probably isn't your immediate problem, but you should always call `fwrite` (and `fread`) with the *second* argument 1 and the *third* argument equal to the amount of data you want to write (or read). Otherwise it is impossible to recover from short writes (or reads). Note also that `sizeof(char)==1` *by definition*, and therefore `sizeof(char)` is a bad code smell. – zwol Sep 24 '13 at 21:28
  • Thank You! But its still not okay. I've added int a=0; right after FILE*p1. The characters've been written in the file, as you can read:Toth Tamas _mcleanup: tos oveToth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas Toth Tamas – Thomas Tóth Sep 24 '13 at 21:47
  • This behavior would be expected (assuming the hypothesis in my answer is correct) for a version of the program that had *both* the while loop and the standalone `fwrite` uncommented. I only tested it as shown, with the standalone `fwrite` commented out. – zwol Sep 24 '13 at 22:59

1 Answers1

0

If I add int a = 0; immediately after FILE *p1;, the while-loop version of the program compiles without complaint, even with maximum warnings, and executes without error on my computer, even under valgrind. You want sizeof("Toth Tamas") - 1 in the fwrite call to prevent NUL bytes from being written to the file, and maybe there should be an \n after "Tamas", and see my earlier comments for other minor problems, but that code seems mostly okay.

However, the commented-out line //fwrite("Toth Tamas",sizeof(char),30,p1); does have a bug: the string constant "Toth Tamas" is only 11 bytes long (counting the terminating NUL), but you have asked fwrite to write 30 bytes, so it will access 19 more bytes beyond the end of the string, triggering undefined behavior. In context, one would expect either a segmentation fault, or garbage written to the file.

And "_mcleanup: tos ov" is 17 bytes long, so if that is (the beginning of) the next string constant in the read-only data segment of your executable, it's a plausible thing to show up as garbage written to the file, which I think is what you are saying happened.

zwol
  • 135,547
  • 38
  • 252
  • 361