overflow in mpz type with a simple mpz_add_ui

Marco Bodrato bodrato at mail.dm.unipi.it
Mon Sep 21 16:43:38 UTC 2020


Ciao,

Il 2020-09-21 18:16 tg at gmplib.org ha scritto:
> overflow.  The overflow detection flags some false positives, which is
> by design.

But maybe we could avoid the false positive at least for the following 
example:

#include <stdio.h>
#include "gmp.h"

int main (void)
{
   mpz_t z;

   mpz_init (z);
   mpz_setbit (z, 0xffffffdf);
   printf ("OK\n");
   mpz_sub_ui (z, z, 123);
   printf ("OK\n");

   return 0;
}

We can avoid it simply moving the REALLOC after the branch.
This may save some allocations in many cases.

The proposed patch follows:

diff -r b851f9336a86 mpz/aors_ui.h
--- a/mpz/aors_ui.h     Thu Sep 17 12:00:00 2020 +0200
+++ b/mpz/aors_ui.h     Mon Sep 21 18:36:33 2020 +0200
@@ -86,21 +86,26 @@

    abs_usize = ABS (usize);

-  /* If not space for W (and possible carry), increase space.  */
-  wp = MPZ_REALLOC (w, abs_usize + 1);
-
-  /* These must be after realloc (U may be the same as W).  */
-  up = PTR (u);
-
    if (usize VARIATION_CMP 0)
      {
        mp_limb_t cy;
+
+      /* If not space for W (and possible carry), increase space.  */
+      wp = MPZ_REALLOC (w, abs_usize + 1);
+      /* These must be after realloc (U may be the same as W).  */
+      up = PTR (u);
+
        cy = mpn_add_1 (wp, up, abs_usize, (mp_limb_t) vval);
        wp[abs_usize] = cy;
        wsize = VARIATION_NEG (abs_usize + cy);
      }
    else
      {
+      /* If not space for W, increase space.  */
+      wp = MPZ_REALLOC (w, abs_usize);
+      /* These must be after realloc (U may be the same as W).  */
+      up = PTR (u);
+
        /* The signs are different.  Need exact comparison to determine
          which operand to subtract from which.  */
        if (abs_usize == 1 && up[0] < vval)




Ĝis,
m

-- 
http://bodrato.it/papers/


More information about the gmp-bugs mailing list