Search code examples
cgmp

Initialising more than two mpz_t using mpz_set_str causes segfault


Anyone know why the following results in a seg fault after the second call to mpz_set_str()? How can I initialise more than two gmp ints from str?

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

int main(int argc, char *argv[]) {

        mpz_t a, b, c;

        mpz_set_str(a, "10", 10);
        printf("gets here a\n");
        mpz_set_str(b, "20", 10);
        printf("gets here b\n");
        mpz_set_str(c, "30", 10);
        printf("gets here c\n");
}

compiled with: gcc -lm -lgmp -o segf segf.c


Solution

  • The documentation for mpz_set_str says:

    5.2 Assignment Functions

    These functions assign new values to already initialized integers (see Initializing Integers).

    ...

    The link goes to

    5.1 Initialization Functions

    The functions for integer arithmetic assume that all integer objects are initialized. You do that by calling the function mpz_init. For example,

    {
      mpz_t integ;
      mpz_init (integ);
      …
      mpz_add (integ, …);
      …
      mpz_sub (integ, …);
    
      /* Unless the program is about to exit, do ... */
      mpz_clear (integ);
    }
    

    As you can see, you can store new values any number of times, once an object is initialized.

    Your code doesn't initialize the variables, so assignment functions such as mpz_set_str produce garbage.