mpz_class possible bug

Torbjorn Granlund tege at swox.com
Mon Oct 2 23:09:13 CEST 2006


Emmanuel Thomé <Emmanuel.Thome at normalesup.org> writes:

  On Mon, Oct 02, 2006 at 10:44:20AM +0200, Peter MALKIN wrote:
  > Dear GMP Developers,
  > 
  > I have encountered a problem when compiling a small c++ program using 
  > gmp version 4.2.1.
  
  [ b = a - b * c  returns garbage ]
  
  confirmed.
  
  The bugs (as there are several) lie in the __gmp_ternary_*mul::eval
  functions, lines 1282 and following of gmpxx.h, and are apparent to the
  C++ illiterate.
  
  Those functions use mpz_set to set z to (the value of) w beforehand.
  Alas, doing so might overwrite valuable input data in the other
  mpz_srcptr operands, in case the pointers are the same.
  
  An easy workaround would be to fallback to using a temporary if
  z->_mp_d == u->_mp_d || z->_mp_d == v->_mp_d. But that would probably
  offset the benefit of doing this complicated ternary op construct. I have
  no precise opinion on this. Here's an example for your case precisely
  (first eval member in __gmp_ternary_submul):
  
    static void eval(mpz_ptr z, mpz_srcptr w, mpz_srcptr v, mpz_srcptr u)
    {
            if (z->_mp_d == u->_mp_d || z->_mp_d == v->_mp_d) {
                    mpz_t temp;
                    mpz_init_set(temp,z);
                    mpz_set(temp, w); 
                    mpz_submul(temp, v, u);
                    mpz_set(z, temp); 
            } else {
                    mpz_set(z, w);
                    mpz_submul(z, v, u);
            }
    }
  
  Obviously, this bug is quite serious anyway.
  
Yes, this was nasty.

The mpz_submul and mpz_addmul functions aren't very important
optimizations, since they too need temporary allocation.

Are all bugs you spotted related to mpz_addmul and mpz_submul,
or did you see other errors?

I suppose we should write something similar to reuse.c, but for the
C++ wrapper testsuite.

-- 
Torbjörn


More information about the gmp-bugs mailing list