Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GMP mpz_array_init is an obsolete function - How should we initialize mpz arrays?

Tags:

c

gmp

Having only used the GNU MP Bignum Library a few times, I was interested to see that the way I had previously allocated/initiated arrays is now obsolete. From Integer Special Functions:

5.16 Special Functions

The functions in this section are for various special purposes. Most applications will not need them. — Function: void mpz_array_init (mpz_t integer_array, mp_size_t array_size, mp_size_t fixed_num_bits)

This is an obsolete function. Do not use it.

This is how I would allocate and initialze an array of mpz_t.

int array_size = 100;
mpz_t *num_arr;
num_arr = malloc(arr_size * sizeof(mpz_t));
mpz_array_init(*num_arr, array_size, 1024);

This still works without and error or warning, btw, but now that this function is listed as obsolete, what is the proper way to allocate an array using GMP in C?

like image 706
AGS Avatar asked Nov 13 '14 12:11

AGS


1 Answers

Simply loop over the array elements and initialize them one by one using mpz_init2 if you want to preallocate memory:

for (i = 0; i < array_size; i++) {
    mpz_init2(num_arr[i], 1024);
}

The problem with mpz_array_init is that it would never release the allocated memory. If you initialize the elements separately, you can free them afterwards:

for (i = 0; i < array_size; i++) {
    mpz_clear(num_arr[i]);
}
like image 136
nwellnhof Avatar answered Sep 20 '22 03:09

nwellnhof