Limitation of the mpz_get_str function

Paul Zimmermann Paul.Zimmermann at inria.fr
Tue Feb 16 14:15:12 UTC 2021


       Hi Christophe,

this issue is known since several years:

https://gmplib.org/list-archives/gmp-bugs/2019-September/004633.html

Paul

> From: Christophe Clavier <christophe.clavier at unilim.fr>
> Date: Tue, 16 Feb 2021 14:22:20 +0100
> 
> Dear GMP developers,
> 
> I currently have to deal with huge numbers (several billions decimal 
> digits) which I need to convert in strings of digits with mpz_get_str.
> I noticed that this function produces an incorrect result when the 
> number of digits exceeds 2^31.
> The reason lies in the loop that scans the buffer computed by 
> mpn_get_str and transforms each digit from an integer to an ascii code :
> 
>    for (i = 0; i < str_size; i++)
>      res_str[i] = num_to_text[(int) res_str[i]];
>    res_str[str_size] = 0;
> 
> As i is of type int, when it is incremented from 2^31-1 to 2^31 it 
> becomes negative.
> For the comparison with str_size, which is of type size_t (i.e. unsigned 
> long int), i is casted in unsigned long int and becomes a large positive 
> value near 2^64.
> Thus the comparison is evaluated to false and the loop early terminates.
> 
> I suggest to modify the type of i to long int or to unsigned long int.
> 
> Regards
> 
> Christophe
> 
> 
> _______________________________________________
> gmp-bugs mailing list
> gmp-bugs at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-bugs


More information about the gmp-bugs mailing list