Search code examples
cgmp

Error in GMP GNU Code?


When I run this code, I have error "Segmentation fault (core dumped)". But without using mpz_get_str, it is okey.

#include<stdio.h>
#include<gmp.h>
int main()
{
char *A;
mpz_t P,Q;
mpz_init(P);
mpz_init(Q);
mpz_set_str(P,"1201858877187548528922917",10);
mpz_set_str(Q,"1248833599132922783100713",10);

mpz_t PHI,E,K,d;
mpz_init(PHI);
mpz_init(E);
mpz_init(K);
mpz_init(d);

mpz_sub_ui(PHI,P,1);
mpz_sub_ui(K,Q,1);
mpz_mul(PHI,PHI,K);
mpz_set_str(E,"37",10);
mpz_gcd(d,E,PHI);
gmp_printf("d=%Zd\n",d);
mpz_invert(d,E,PHI);
gmp_printf("d=%Zd\n",d);
A=mpz_get_str(A,2,d);

mpz_mul(K,d,E);
mpz_sub_ui(K,K,1);
mpz_divexact(K,K,PHI);



}

Solution

  • You should initialize your char *A to NULL or 0, otherwise (if it's not NULL or 0 by chance), GMP will try to write into a random memory address, which will cause a segfault.

    From the GMP documentation: http://gmplib.org/manual/Converting-Integers.html

    If str is NULL, the result string is allocated using the current allocation function (see Custom Allocation). The block will be strlen(str)+1 bytes, that being exactly enough for the string and null-terminator.

    If str is not NULL, it should point to a block of storage large enough for the result, that being mpz_sizeinbase (op, base) + 2. The two extra bytes are for a possible minus sign, and the null-terminator.