libgmp exceptions

Raul Miller rauldmiller at
Sun Apr 2 05:36:24 CEST 2023

It seems to me that exceptions in libgmp could be handled returning a
"decorated" zero value.

Here, for example, the __mp_d field of the mpz_t would contain
information about the error (or a no-error value or range of values)
when the zero result represents an error case.

For backwards compatibility, performance-wise, libgmp would have to be
compiled with a flag such as -DZEROERRORS to get this sort of
exception treatment. Perhaps there could also be a runtime switch
(which defaulted off) for systems like Debian which have diverse

All return results would then need a test for a zero size followed by
a test for an error result (perhaps least significant bit in __mp_d
being set indicating an error).

If someone used this variant of libgmp without adequate checks, they
would receive spurious zero results (or possibly a segfault if they
dereferenced the __mp_d pointer) for error cases.

Note also that any robust system which currently uses libgmp is going
to have to have some sort of treatment for errors already -- perhaps
with guard conditions before calling libgmp routines. So I do not
anticipate too much pain from this approach.


Raul Miller

More information about the gmp-devel mailing list