GMP terminates when out of memory

Roberto Bagnara bagnara at
Sun Dec 28 10:44:49 CET 2008

Bjarke Roune wrote:
>> 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,
> Thanks for sharing this interesting solution. How have you tested it?

Yes, of course :-)

But not thoroughly.

> E.g. have you tried it with integers of varying sizes, where you at
> some point make allocation fail, and then check that all the GMP
> integers are in a valid state and that no memory is leaked?

Yes, we have one test in our testsuite that simulates virtual memory
exhaustions and running it with valgrind does not reveal any memory
leak.  In addition, we have used for years this facility in our
program analyzers and we never detected a state violation.

> Adding exceptions to my library meant that suddenly most of the lines
> with "new" in them could be made to leak memory, and in many cases
> this was not trivial to fix. It is wonderful if GMP has no or few
> exception-triggered leaks just by luck.

Maybe GMP does leak memory (and it would be nice to fix that), but
for the kind of applications this is not a big deal.  I mean, our
tools (program analyzers) react to memory exhaustion by freeing
memory and switching to a simpler analysis technique;  if virtual
memory is exhausted again then even drastic measure are taken.
A particularly unfortunate run would not involve more than a few
hundreds virtual memory exhaustions, and even if the same number
of GMP integers is leaked, no one would notice.  Note also that
we only use the simplest arithmetic functions.

So, for us the main dream would be for GMP to guarantee a safe
state: I hope this is not too difficult to achieve.  Absence of
memory leaks (at least for the simplest functions) is desirable,
but not crucial.
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