2

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);



}
1
  • If you run your program with Valgrind it will tell you where the error is. Valgrind is a good first tool to reach for when dealing with unexpected segmentation faults. Commented Oct 31, 2012 at 3:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.