# memory allocation

Marc Glisse marc.glisse at inria.fr
Thu Jun 3 21:48:21 CEST 2010

```On Thu, 3 Jun 2010, Paul Zimmermann wrote:

> the following program gives with GMP 5.0.1 on a 64-bit computer:
>
> tarte% ./a.out
> z=559571982226613223396 alloc=3 size=2
> r=0 alloc=1 size=0
> r=32571376198 alloc=3 size=1
>
> Why does GMP allocate 3 limbs for z (which fits into 2 limbs), and allocate
> 3 limbs for r (which fits into 1 limb)?

Hello,

does it cause trouble somehow? It is only a constant number (1 for the
string, 2 for the division, in the worst case) of extra limbs, the
documentation mentions this can happen and many gmp functions do it (the
worst being maybe z-z which allocates size(z)+1).

Currently the division code only looks at size(number) and shift/64. For
(2^128-1) shifted by 64 to the right and rounded towards +inf (ie size==2
and shift/64==1), this gives 2^64, which requires 2 limbs (2-1+1). In your
exemple, this formula says 2-0+1==3 limbs to be safe. Yes, it is funny
that shifting to the right by less than 64 implies allocating something
bigger than the argument.

There are many places where the required size could be computed more
tightly...

> #include <stdio.h>
> #include "gmp.h"
>
> main()
> {
>  mpz_t z, r;
>
>  mpz_init_set_str (z, "559571982226613223396", 10);
>  gmp_printf ("z=%Zd alloc=%u size=%u\n", z, z->_mp_alloc, z->_mp_size);
>  mpz_init (r);
>  gmp_printf ("r=%Zd alloc=%u size=%u\n", r, r->_mp_alloc, r->_mp_size);
>  mpz_fdiv_q_2exp (r, z, 34);
>  gmp_printf ("r=%Zd alloc=%u size=%u\n", r, r->_mp_alloc, r->_mp_size);
>  mpz_clear (r);
>  mpz_clear (z);
> }

--
Marc Glisse
```