Pregunta

This is a follow-up question to a previous question (now that the actual issue is different):

int main() 
{
    mpz_t p, q, n, phi_n, e, d; 
    mpz_inits(p, q, n, phi_n, e, d, NULL);

    generate_pq(p,q);
    compute_n(n,p,q);

    compute_phiN(phi_n,p,q);
    mpz_clear(p,q,NULL);

    select_e(e,phi_n);

    compute_d(d,e,phi_n);
    mpz_clear(phi_n);

    mpz_t* m;
    int size=0;
    store_m(m,size);

    mpz_t* c;
    encrypt(c,m,size,e,n);
    return 0;
}

Here are the relevant functions:

void store_m(mpz_t m[], int& size) 
{ /* m = original message */
    printf("\nMessage: ");
    char* buffer = new char[128];
    cin.getline(buffer,128);
    size = strlen(buffer); //size = buffer
    m = new mpz_t[size];
    for(int i=0; i<size; i++) {
        mpz_init(m[i]);
        mpz_set_ui(m[i],(int)buffer[i]);
    }
    delete buffer;
}

void encrypt(mpz_t*& c, mpz_t m[], const int size, 
                 const mpz_t e, const mpz_t n)
{ /* c = cipher */
    cout << "1" << endl;
    c = new mpz_t[size];
    cout << "2" << endl;
    for(int i=0; i<size; i++) {
        cout << "3" << endl;
        mpz_init(c[i]);
        cout << "4" << endl;
        mpz_powm(c[i],m[i],e,n);
        cout << "5" << endl;
        mpz_clear(m[i]);
        cout << "6" << endl;
    } /* c = m^e(mod n) */
    cout << "7" << endl;
}

When I execute, the program goes into encrypt() but seg faults at the 4th cout.

¿Fue útil?

Solución

Remember C++ is pass-by-value unless you explictly say you're passing by reference using the & operator. In store_m() you are allocating and assigning to m inside the function. That won't work since you're passing m by value. As a result the main() function never sees the assignment to m since store_m() has only a local copy of m. You are therefore passing an uninitialized variable to encrypt(). Either allocate m in main() or declare store_m() like so:

void store_m( mpt_t*& m, int& size);

BTW: You're not segfaulting at the 4th cout. You're segfaulting right after when the encrypt() function prepares to call mpz_powm(). The actual crash is the dereference m[i] (since m is unitialized).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top