Question about mpz_array_init and dynamic array

Jürgen Hochwald jh at cfjh.de
Thu Sep 27 22:10:31 CEST 2007


Hi,

I've some problems with mpz_array_init with a dynamic memory allocation. I 
need a large numer of mpz_t's but the size is not known at design time.

After some try and error I can initialisize the array with mpz_array_init but 
I have come problems acessing the elements.

Can someone give some hints ord a code example hoe to do this ?

------------

#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>

mpz_t *ar; // the array
mpz_t *p; // pointer to access single element

int main(void) {
int ar_size=100; // here static, later read from file

  // init
  printf("sizeof(mpz_t)=%d\n",sizeof(mpz_t));
  ar=(mpz_t*)malloc(sizeof(mpz_t)*ar_size);
  mpz_array_init(*ar, ar_size, 20);

  // seems to work
  p=ar;
  mpz_set_str(*p, "1234567274827482847847487484783472384738",10);
  gmp_printf("p=%Zd\n",*p);

  // failure
  p=ar+1; //sizeof(mpz_t);
  mpz_set_str(*p, "96879678697867986786787967869",10);
  gmp_printf("p=%Zd\n",*p);

  free(ar);
}

compiles without error  (gcc gmp_arr_test.c -lgmp -o gmp_arr_test)

output (running on Suse Linux 10.0 64 bit): 
> ./gmp_arr_test
sizeof(mpz_t)=16
p=12345672748274828478474874847834723847384723487243872428742847328472348724872482748
*** glibc detected *** realloc(): invalid pointer: 0x00000000005017f0 ***
Abgebrochen  (<- english: aborted, german Suse)

Jürgen
www.wetterstation-porta.info


More information about the gmp-discuss mailing list