Search code examples
cgmp

SIGSEGV with GMP


I'm trying to generate a number e, prime with the product of two number(p and q).

But i can't even run the code... i got a segmentation fault, i'm sure that is something simple/importante but i really can't figure out:

void PubKeyED(mpz_t e,mpz_t d,mpz_t p,mpz_t q){
    unsigned long int cmp,cont,seed;
    mpz_t pq,gcdpq;
    cont=1;
    mpz_inits(pq,gcdpq);
    mpz_sub_ui(p,p,cont);
    mpz_sub_ui(q,q,cont);
    mpz_mul(pq,p,q);
    seed = time(NULL);
    gmp_randstate_t init;
    gmp_randinit_mt(init);
    gmp_randseed_ui(init, seed);
    do
    {
        mpz_urandomm(e, init, pq);
        mpz_gcd (gcdpq, e, pq);
        cmp=mpz_cmp_ui(gcdpq,cont);
        if (cmp==0)
        {
            cont=0;
        }
    } while (cont);
}

int main(){
    mpz_t e,d,p,q;
    mpz_inits(p,q,e,d);
    mpz_set_ui (p, 17);
    mpz_set_ui (q, 23);
    PubKeyED(e,d,p,q);

}

I am new to gmp, and not very comfortable with C.


Solution

  • If you read the documentation for mpz_inits you will see that it

    Initialize a NULL-terminated list of mpz_t variables

    [Emphasis mine]

    The problem with your code is that you pass an argument list that is not "NULL-terminated".

    You need to replace your calls like so:

    mpz_inits(p,q,e,d,NULL);  // End argument list with a null pointer