mpz_class possible bug

Emmanuel Thomé Emmanuel.Thome at normalesup.org
Mon Oct 2 21:54:36 CEST 2006


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.

Regards,

E.


More information about the gmp-bugs mailing list