Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win10 broke printf function

#include <stdio.h>
int main()
{
    float f = 1717.7890625;
    printf( "%.6f", f );
    return 0;
}

I compiled this code with Visual Studio 19 (16.9.2) for x64 arch and ran the result on two my Windows 10 PCs:

  1. Version 1909 (OS build 18363.1440) -> Debug and Release: 1717.789063
  2. Version 2004 (OS build 19041.867) -> Debug: 1717.789063 Release: 1717.789062

What is the cause of the difference between the Debug and Release results on new version? How can I fix it to make results identical on both versions?

Addition: The code:

#include <stdio.h>
int main()
{
    double f = 0.25;
    printf( "%.1f", f );
    return 0;
}

has the same behavior on new vs old Win10 versions. I suggest, that's an error in newer ucrtbase.dll version

like image 406
Ivan Ivlev Avatar asked Mar 22 '21 16:03

Ivan Ivlev


1 Answers

I found the cause of such different behavior of program between windows versions and debug/release modes.

The new windows update (19041.* if I understand correctly) changed rounding rules for fractional part of floating point types: previously it was rounding to greater in case of end with 5: 1.25 -> 1.3, but now it's rounding to nearest even: 1.25 -> 1.2, 1.35 -> 1.4.

To understand the difference between debug and release on new Win 10 version it's needed to notice about the ucrtbase.dll usage and update rules.

  1. Debug and release versions of every application use ucrtbase.dll or ucrtbased.dll from C:\Windows\System32 or C:\Windows\SysWOW64
  2. It's release version (ucrtbase.dll) is a part of Windows 10 and can be updated only with Windows update. But it's debug version (ucrtbased.dll) is not updated with Win 10 update, but can be updated with installation of newer Windows 10 SDK (for example, in Visual Studio Installer).

So, the solution is to install new Windows 10 SDK on new Windows 10 version to achieve the same behavior or switch printf() function to fmt::printf() function from https://github.com/fmtlib/fmt, for example, to make result to be the same on all windows versions.

like image 140
Ivan Ivlev Avatar answered Nov 10 '22 23:11

Ivan Ivlev