Question about mpz_set_str

delta trinity
Mon, 06 Jan 2003 14:12:32 -0500

1 - Internally, the re-allocation depend on your memory manager.

Here's a description of Borland C++ Builder help on 'realloc' function:


Reallocates main memory.

realloc attempts to shrink or expand the previously allocated block to size 
bytes. If size is zero, the memory block is freed and NULL is returned. The 
block argument points to a memory block previously obtained by calling 
malloc, calloc, or realloc. If block is a NULL pointer, realloc works just 
like malloc.

realloc adjusts the size of the allocated block to size, copying the 
contents to a new location if necessary.


This is standard C so should be the same across all compilers.  And yes, the 
old memory block is freed if the block have to be transfered to a new, 
larger buffer.

2 - According to section 3.6, 2nd paragraph, of GNU MP 4.1 document, yes :-)

To take more direct control on the allocation/de-allocation of memory, you 
can check section 14 of GMP 4.1 doc ('Custom Allocation').  You can overide 
the alloc, realloc and free memory functions to implement your own memory 
manager.  But that won't lower the frequency at which those functions are 

If you want to adjust the number of times the memory is re-allocated, you 
can directly use the mpz_realloc2 funcion.  You could, for example, check if 
the variable is big enough and if not, increasy by a factor of 128 bits for 
example.  You could also 'manually' decrease the size of oversized mpz_t 
structs.  The worst that can happen is that if you decrease memory too much 
so that the mpz_t struct value can't fit in the allocated memory block, it's 
value will be reset to zero.  mpz_sizeinbase can be used to know how many 
bits are required for any given value.

>From: Minh Nguyen <>
>To: Kevin Ryde <>
>Subject: Re: Question about mpz_set_str
>Date: Mon, 6 Jan 2003 07:10:29 -0800 (PST)
>Thanks, two more questions
>1/ When GMP reallocates a buffer, would the old buffer be freed?
>2/ Is it true that GMP only considers to enlarge a buffer, but never 
>considers to shorten it?
>  Kevin Ryde <> wrote:Minh Nguyen writes:
> >
> > Why does GMP have to reallocate memory when it is not necessary?
>Generally to keep size calculations simpler and smaller. There's no
>sense making a complicated calculation just to shave one or two limbs
>in certain cases.
>It's left up to each mpz function to decide what it would like to
>have, it just has to call MPZ_REALLOC and friends.
>Do you Yahoo!?
>Yahoo! Mail Plus - Powerful. Affordable. Sign up now

The new MSN 8: smart spam protection and 2 months FREE*