Extra zero byte converting mpz_t to a string

Hans Aberg haberg-1 at telia.com
Mon Apr 20 12:31:31 UTC 2015


> On 20 Apr 2015, at 11:35, Niels Möller <nisse at lysator.liu.se> wrote:
> 
> Hans Aberg <haberg-1 at telia.com> writes:
> 
>> Right, but you would not would want to compute it if the current
>> free_function() does not use it.
> 
> If that matters, I'd suggest allocating it before invoking mpz_get_str.

This is what I did, in C++:
    std::string str(int base = 10) const {
      char* cs = new char[mpz_sizeinbase(value_, base) + 2];
      mpz_get_str(cs, base, value_);
      std::string str_r(cs); delete[] cs;
      return str_r;
    }

But then, in view of this thread, I thought I might try letting mpz_get_str() do the allocation, but realized the problem of finding deallocation size in case someone would implement it.

> If you pass NULL to mpz_get_str, you also have the cost that it may do a
> pretty useless reallocation to shrink the area from strlen(s)+2 to
> strlen()+1, in case the initial allocation, based on mpz_sizeinbase,
> returned a one-off size.

Another thing is that the C++ std::strings class seems to require two allocations, as one does not get access to its internal buffer fro writing. This is not so important, as writing strings is normally rare.

> That said, I'd prefer to remove the size argument fom the free function and
> the old size argument for the realloc function. But that's an interface
> change (see https://gmplib.org/devel/incompatibility.html).

That is a reason I brought it up: current size arguments are incompatible with the standard C allocation model.



More information about the gmp-bugs mailing list