Invalid read in mpz_sub

Vincent Lefevre vincent at
Thu Apr 7 07:44:15 UTC 2016

On 2016-04-06 17:39:21 +0200, Torbjörn Granlund wrote:
> Miha Marolt <miham at> writes:
>   In some cases a previously freed memory is read inside the mpz_sub
>   function. Here is an example program that demonstrates the
>   problem:
> The bug is in your code.
> When passing x by value, you make copies of the two contained mpz_t
> variables, including pointers.  Then you cause reallocation of the
> original variables, making pointer your copies point to stale data.

However, the GMP manual says:

[...] Here are some examples of how to declare such integers:

     mpz_t sum;

     struct foo { mpz_t x, y; };

     mpz_t vec[20];

and doesn't forbid to copy the structure, for instance. I think it
would be worth to mention that using several copies of a mpz_t is
forbidden (or a write operation invalidates the other copies),
here or in one of the next sections (BTW, the MPFR manual should
be clarified too).

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

More information about the gmp-bugs mailing list