robinchm
robinchm

Reputation: 109

fprintf 0 gives unexpected results under windows MinGW

I am currently porting a C project from linux to windows, during which I encounter a weird error. In the source file it has these two lines:

    fprintf(fp, "%4d %11.6f %11.6f %11.6f\n", cell->total_atom_no, 0, 0, 0);
    printf("%4d %11.6f %11.6f %11.6f\n", cell->total_atom_no, 0, 0, 0);

To be clear, the file is opened in binary mode "wb". The output in the file is:

      18    0.000000    0.000000 166818935138251830000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000

While the output in the command line is:

      18    0.000000    0.000000    0.000000

The command line version is correct. But under linux both the file and command line will give the correct output. I cannot make a reproducable code as if I try a simple code:

    int a = 18;
    fprintf(fp, "%4d %11.6f %11.6f %11.6f\n", a, 0, 0, 0);

It will give the expected output. Neither can I upload the original file as it is thousand lines long. But it passes compilation without error, btw.

At this point I am really confusing, how can printing 0 cause error? Any hints to the source of error will be greatly appreciated.

Update 1:

The problem seemes to relate to Gtk library. This program has two version, one command line, the other GUI programmed in Gtk+2. Both versions use the same file that contains the above codes, but only the GUI version deliver this error.

Then it seems to be a problem related to Gtk libraries but I have no clue to debug furthur.

Update 2:

I tried the following two fixes

    fprintf(fp, "%4d %11.6f %11.6f %11.6f\n", cell->total_atom_no, 0, 0, 0.0);
    fprintf(fp, "%4d %11.6f %11.6f %11.6f\n", cell->total_atom_no, 0, 0, (float)0);

The error still persists. I can print those zeros as srings without problem, but I need to know what is going wrong.

Upvotes: 1

Views: 373

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

Your call to printf leads to undefined behavior. The reason is that printf and family expects double arguments for the "%f" format. You give it three int values instead.

As int is (normally on modern platforms) 32 bits while double is 64 bits, the printf will go outside the actual data provided to the function, and fetch seemingly random data from the stack possibly beyond its limits.

Upvotes: 1

Related Questions