bug in gmp_fprintf?

Leif Leonhardy not.really at online.de
Mon Nov 23 18:05:55 UTC 2015

paul zimmermann wrote:
>        Hi,
> on https://gmplib.org/list-archives/gmp-discuss/2005-August/001787.html I read:
>> "Support at the mpn and mpz levels for operands of up to 2^56 bits
>> (on 64-bit machines). Current limits are: on 32-bit machines, 2^31 bits;
>> on 64-bit machines, 2^37 bits".
> However with the program below I get on a 64-bit machine:
> zimmerma at tomate:/tmp$ ./a.out 8589934589
> GMP version 6.1.0
> P has 8589934589 bits
> P has 1 bits
> If I replace gmp_fprintf (fp, "%Zx\n", P) by mpz_out_str (fp, 16, P) I get:

Note that the printf() functions are logically limited by their return
type, which is int, as they are supposed to return the number of
characters written, hence cannot "correctly" write more than 2^31-1
characters on typical 32-bit as well as 64-bit machines.

The number gmp_fprintf() returns for the input above is negative, which
should indicate an error (and the number of characters [to be] written
in fact exceeds 2^31-1, it's 2147483649 = 2^31+1).

Since mpz_out_str() in contrast returns the number of bytes written as a
*size_t*, it /should/^TM be slightly less limited on 32-bit and really
less limited on 64-bit machines, but apparently isn't.  I.e., it appears
to have similar limitations, which is IMHO a bug.  (Haven't looked at
the code though.)

> zimmerma at tomate:/tmp$ ./a.out 8589934589
> GMP version 6.1.0
> P has 8589934589 bits
> P has 8589934581 bits
> Thus we cannot correctly print/read numbers of 2^33 bits.

2^33 bits?  I'd say numbers with approximately more than 2^31-1
*digits*.  (The number of bits depends on the base.)  Given 8589934584,
your program works for me as expected with both gmp_fprintf() and
mpz_out_str() on a 64-bit machine.

With 8589934589, the output is incorrect*, but gmp_fscanf() seems to work.


* for gmp_fprintf(), a blank followed by 2147483647 zeroes ('0') and a
newline, for mpz_out_str(), '1fff...ffef'.

More information about the gmp-bugs mailing list