Lazy mpz allocation

Niels Möller nisse at
Mon Sep 28 10:43:21 UTC 2015

"Marco Bodrato" <bodrato at> writes:

>> I'd like a sort of "copy-on-write" interface, that allocates the needed
> I looked into the code and realised that my proposal requires an
> MPZ_REALLOC or if(ALLOC(x)==0) branch in ANY place where we write into an
> mpz_t. E.g. mpz_combit starts with:
>   if (limb_index + 1 < SIZ(x)) {
>     PTR(x)[limb_index] ^= bit;
>     return;
>   }

Good point. I'd say we postpone the "copy-on-write" thing for now. And
only support the following cases:

1. alloc > 0: Normal case, |size| <= alloc, reallocated as needed.

2. alloc == 0, size == 0: Initial lazy state, produced by mpz_init.
   Allocated on first write.

3. alloc == 0, size != 0: Allowed for input (read-only) mpz:s. Produced
   by mpz_roinit. Any attempt at writing the variable is invalid, and
   should call abort in all cases where checking for this case is cheap

One corner case is what should be produced by mpz_roinit with a zero
input. After normalization we get size == 0. The intended meaning is
that of case (3), but if it is misused as an output variable, it will be
treated as case (2), and the allocated storage will leak. But I think it
is acceptable to have some random bad things happen on misuse.


Niels Möller. PGP-encrypted email is preferred. Keyid C0B98E26.
Internet email is subject to wholesale government surveillance.

More information about the gmp-devel mailing list