mpz_limbs_modify doesn't clear new limbs

Vincent Lefevre vincent at vinc17.net
Thu Jan 2 13:30:50 CET 2025


On 2025-01-02 11:41:51 +0100, Ivo maffei wrote:
> This is indeed my issue.
> 
> If I call xptr = mpz_limbs_modify(x,n), then xptr[0..mpz_size(x)) is the
> value of x, but xptr[0..n) might contain the unused limbs.
> When reading the documentation, I was expecting the whole array xptr[0..n)
> to represent the value of x, but this is not the case.
> As a side effect, the code ``mpz_limbs_modify(x,n); mpz_limbs_finish(x,
> n);'' can alter the value of x even if n > mpz_size(x).
> The above "feels wrong", but if it's not considered a bug, then perhaps the
> manual should make this clear for newbies like me.

You should not use mpz_limbs_finish just after mpz_limbs_modify.
The documentation of mpz_limbs_modifympz_limbs_finish says:

  Used after writing to the limb array pointer returned by
       ^^^^^^^^^^^^^
  'mpz_limbs_write' or 'mpz_limbs_modify' is completed.  The array
  should contain abs(S) valid limbs, representing the new absolute
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  value for X, and the sign of X is taken from the sign of S.

So it's up to you to complete the array obtained via mpz_limbs_modify.
There is an example in the documentation of mpz_limbs_finish:

     void foo (mpz_t x)
     {
       mp_size_t n, i;
       mp_limb_t *xp;

       n = mpz_size (x);
       xp = mpz_limbs_modify (x, 2*n);
       for (i = 0; i < n; i++)
         xp[n+i] = xp[n-1-i];
       mpz_limbs_finish (x, mpz_sgn (x) < 0 ? - 2*n : 2*n);
     }

-- 
Vincent Lefèvre <vincent at vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)


More information about the gmp-discuss mailing list