for循环中的RSA mpz_powm():seg fault [英] RSA mpz_powm() in for-loop: seg fault
问题描述
这是针对上一个问题的后续问题(现在问题不同):
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;
}
以下是相关函数:
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;
}
当我执行时,程序进入 encrypt
When I execute, the program goes into encrypt() but seg faults at the 4th cout.
推荐答案
记住C ++是pass-by-value,除非你明确地说使用&
运算符通过引用传递。在 store_m()
中,您将分配并分配到函数中的 m
。这不会工作,因为你通过值 m
。因为 main()
函数从不会看到赋给 m
,因为 store_m
只有本地副本 m
。因此,您将未初始化的变量传递给 encrypt()
。在中分配
m
或者声明 store_m()
like like:
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:你不是在第四个 cout
处发生错误。当 encrypt()
函数准备调用 mpz_powm()
时,就会立即执行segfault。实际崩溃是取消引用 m [i]
(因为 m
被单位化)。
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).
这篇关于for循环中的RSA mpz_powm():seg fault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!