http://www.perlmonks.org?node_id=11107302

syphilis has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

The demo:
use strict; use warnings; use Inline C => Config => BUILD_NOISY => 1, ; use Inline C => <<'EOC'; void foo(SV * arg) { SV * keysv = sv_newmortal(); /* Make sure arg is an NV */ if(!SvNOK(arg)) croak("Not a valid arg passed to foo for this demo") +; printf( "NV: %.19" NVgf, SvNV(arg)); sv_setpvf(keysv, "%.19" NVgf, SvNV(arg)); printf("\nsv: %s\n\n", SvPV_nolen(keysv)); } void bar(SV * arg) { SV * keysv = sv_newmortal(); char buff[30]; /* Make sure arg is an NV */ if(!SvNOK(arg)) croak("Not a valid arg passed to bar for this demo" +); sprintf(buff, "%.19" NVgf, SvNV(arg)); printf("NV: %s", buff); sv_setpvf(keysv, "%s", buff); printf("\nsv: %s\n\n", SvPV_nolen(keysv)); } EOC my @v = (2 ** 55, 2 ** 56, 2 ** 57, 2 ** 58, 2 ** 63); foo($_) for @v; print "################\n\n"; bar($_) for @v;
On Windows (perl-5.30.0), output is as I expect:
NV: 36028797018963968 sv: 36028797018963968 NV: 72057594037927936 sv: 72057594037927936 NV: 144115188075855872 sv: 144115188075855872 NV: 288230376151711744 sv: 288230376151711744 NV: 9223372036854775808 sv: 9223372036854775808 ################ NV: 36028797018963968 sv: 36028797018963968 NV: 72057594037927936 sv: 72057594037927936 NV: 144115188075855872 sv: 144115188075855872 NV: 288230376151711744 sv: 288230376151711744 NV: 9223372036854775808 sv: 9223372036854775808
Note that foo() and bar() produce identical outputs.

However, on Ubuntu and Debian (perl-5.30.0), while bar() produces the same output as above, foo() does not:
NV: 36028797018963968 sv: 36028797018963968 NV: 72057594037927936 sv: 72057594037927936 NV: 144115188075855872 sv: 1.4411518807585587e+17 NV: 288230376151711744 sv: 2.8823037615171174e+17 NV: 9223372036854775808 sv: 9.2233720368547758e+18 ################ NV: 36028797018963968 sv: 36028797018963968 NV: 72057594037927936 sv: 72057594037927936 NV: 144115188075855872 sv: 144115188075855872 NV: 288230376151711744 sv: 288230376151711744 NV: 9223372036854775808 sv: 9223372036854775808
In foo() I assign "%.19" NVgf, SvNV(arg) directly to the SV "keysv" via sv_setpvf.

In bar() I assign "%.19" NVgf, SvNV(arg) directly to the string buffer "buff" via sprintf.
And then I assign "buff" to "keysv" via sv_setpvf.

I'm very surprised at foo's different behaviour on Linux - to the extent that it looks buggy, to me.
Any thoughts on that ?

Cheers,
Rob

PS
The perls I'm running are perls whose NV ($Config{nvtype}) is 'double'.
And the behaviour I'm wanting is that exhibited by bar(). (The bar function is actually my workaround for the problem that foo() presents.)
Debian Wheezy and Ubuntu-18.04 suffer from this problem, but freebsd-12.0 does not. (Those three systems, and windows 7, are the only systems I've tested.)