Search code examples
cgmp

Why is Segmentation fault when using GMP?


I am using the GMP. My program can build successfully, But run failed. The following is error things:

a=1231231231231231
res^n != a
Segment fault

All codes in my program is:

#include <gmp.h>
#include <stdio.h>
int main()
{
    mpz_t a,res;
    unsigned long int n = 123;

    char str1[] = "1231231231231231";
    mpz_init_set_str(a, str1, 10);
    gmp_printf("a=%Zd\n",a);


    mpz_init(res);

    if(mpz_root(res, a, n)){
        printf("res^n == a\n");
    }
    else{
        printf("res^n != a\n");
    }

    mpz_clears(a,res);
    return 0;
}


Solution

  • You have to call mpz_clears() like:

    mpz_clears(a,res, NULL);
    

    Here's what the documentation says:

    Function: void mpz_clears (mpz_t x, ...)
    
        Free the space occupied by a NULL-terminated list of mpz_t variables.