GMP terminates when out of memory

Roberto Bagnara bagnara at
Fri Dec 26 19:32:55 CET 2008

Torbjorn Granlund wrote:
> "Bjarke Roune" <bjarke at> writes:
>   I am writing a C++ library, and it has been very convenient and
>   efficient to use GMP. The thing is that I would like my library to
>   recover from running out of memory, and using GMP seems to make this
>   impossible, since the GMP documentation at
>   states that
>   "There's currently no defined way for the allocation functions to
>   recover from an error such as out of memory, they must terminate
>   program execution. A longjmp or throwing a C++ exception will have
>   undefined results. This may change in the future."
>   I am wondering whether this is likely to change soon, or if it is more
>   like "if sometime in the future someone throws a nice patch at us,
>   we'll consider applying it" ?
> What sort of behaviour would you suggest?

Memory allocated by the failed computation should be released, and the
state should be set to a valid one that allows the computation to proceed.

> I suppose much of this can be done with the custom allocation interface
> already.

Yes.  This is what we are doing since several years:

1) We compile GMP with -fexceptions added to CPPFLAGS (several GNU/Linux
    distribution do that systematically for any package).  This way exceptions
    raised by C++ code can be propagated through C code.  It seems that
    this propagation works for GMP, at least for the (few) GMP functions
    we use.

2) We do

      mp_set_memory_functions(cxx_malloc, cxx_realloc, cxx_free)


      extern "C" void*
      cxx_malloc(size_t size) {
        void* p = malloc(size);
        if (p != 0 || size == 0)
          return p;

        throw std::bad_alloc();

      extern "C" void*
      cxx_realloc(void* q, size_t, size_t new_size) {
        void* p = realloc(q, new_size);
        if (p != 0 || new_size == 0)
          return p;

        throw std::bad_alloc();

      extern "C" void
      cxx_free(void* p, size_t) {

Of course we know that, in light of

the GMP specifications do no guarantee the behavior we are
relying upon.  However, years of use never revealed a problem:
the fragment of GMP we rely upon seems to do the right thing.
It would be great if GMP could, in the future, ensure
that the right thing systematically happens: C++ users
(of any library, not just GMP) increasingly expect that
std::bad_alloc can be dealt with gracefully.
All the best,


Prof. Roberto Bagnara
Computer Science Group
Department of Mathematics, University of Parma, Italy
mailto:bagnara at

More information about the gmp-discuss mailing list