[PATCH] mini-gmp: pass correct old_size to custom reallocate function

Niels Möller nisse at lysator.liu.se
Sat Mar 7 08:42:10 UTC 2020


minux <minux.ma at gmail.com> writes:

> mini-gmp currently always passes old_size == 0 to the custom
> reallocate function, causing custom allocators for GMP that use
> old_size to determine the amount of data to copy data to newly
> allocated space to malfunction with mini-gmp.

That's right. Deleting that feature from the main gmp library is under
consideration (for some future release breaking compatibility with
current version), see https://gmplib.org/devel/incompatibility.html

> According to GMP documentation chapter 13 for reallocate_function:
> "The block may be moved if necessary or if desired, and in that case
> the smaller of old_size and new_size bytes must be copied to the new
> location."

As I understand the docs, the intention is *not* that old_size for
realloc is the amount of data currently in use, which I agree would be
useful. As I understand it, it is required that the old_size argument is
same value passed as allocation size when the old block was previously
allocated, regardless of how much is actually in use. 

To be concrete, if you look at GMP's _mpz_realloc function, in
mpz/realloc.c, or passes the mpz's _mp_alloc as old_size, not the
_mp_size field.

The requirement that realloc and free gets the original allocation size
as argument is easy in most cases, e.g., in _mpz_realloc, but causes
additional complexity in a few cases, In particular, for mpz_get_str
with a NULL input buffer, mini-gmp's implementation of mpz_get_str
sometimes allocates a byte extra, and the application has no way of
knowing that and passing the original allocation size when later
deallocating the buffer. GMP's implementation deals with this case using
an extra realloc, to guarantee that the allocation size equals strlen +
1.

The reason mini-gmp behaves differently here is that (i) the old_size
argument appear to be rarely used (because memory alocators typically
maintains their own metadata about alloctions), and (ii) to eliminate
some complexity from mpz_get_str.

Regards,
/Niels

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


More information about the gmp-devel mailing list