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.
Remember C++ is pass-by-value unless you explictly say you're passing by reference using the
&
operator. Instore_m()
you are allocating and assigning tom
inside the function. That won't work since you're passingm
by value. As a result themain()
function never sees the assignment tom
sincestore_m()
has only a local copy ofm
. You are therefore passing an uninitialized variable toencrypt()
. Either allocatem
inmain()
or declarestore_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 theencrypt()
function prepares to callmpz_powm()
. The actual crash is the dereferencem[i]
(sincem
is unitialized).