5

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?

AGS
  • 14,288
  • 5
  • 52
  • 67

2 Answers2

10

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]);
}
nwellnhof
  • 32,319
  • 7
  • 89
  • 113
  • What about free(num_arr) at the end, can I use that instead of going through the array with mpz_clear? – nullgraph Jan 14 '15 at 00:45
  • 3
    No, `mpz_clear` is needed to free the memory allocated for each `mpz_t`. Additionally, you have to call `free(num_arr)` to free the array. – nwellnhof Jan 14 '15 at 12:28
  • [According to the documentation](https://gmplib.org/manual/Initializing-Integers.html), calling `mpz_init2` instead of `mpz_init` is "never necessary; reallocation is handled automatically by GMP when needed." – SO Stinks Mar 21 '20 at 11:15
  • @Dr.PersonPersonII But as the next paragraph says, it avoids reallocations if the size is known in advance. – nwellnhof Mar 21 '20 at 15:03
-1

What about different method :

/*
http://scicomp.stackexchange.com/questions/3581/large-array-in-gmp
gcc a.c -lgmp
*/
#include <stdlib.h> // malloc
#include <stdio.h>
#include <gmp.h>

#define LENGTH 100000

int main ()
{       
      /* definition */
    mpz_t *A;
    mpz_t temp;

    mpz_init(temp);

    /* initialization of A */
    A = malloc(LENGTH * sizeof(mpz_t));
    if (A==NULL) {
          printf("ERROR: Out of memory\n");
          return 1;
                 }
    // assign
    mpz_set_ui(temp, 121277777777777777); // using temp var 
    mpz_set(A[4], temp);
    mpz_set_str(A[5], "19999999999999999999999999999999999999999999999999992",10); // using string if number > max 

     // check
    gmp_printf ("%Zd\n",A[4]); // 
    gmp_printf ("%Zd\n",A[5]); // 


    /* no longer need A */
   free(A);
   mpz_clear(temp);

        return 0;
}

Is it good ?

Adam
  • 1,254
  • 12
  • 25