使用 mpz_set_str 初始化两个以上 mpz_t 会导致段错误
Initialising more than two mpz_t using mpz_set_str causes segfault
任何人都知道为什么在第二次调用 mpz_set_str() 后以下会导致段错误?如何从 str 初始化两个以上的 gmp 整数?
#include <gmp.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
mpz_t a, b, c;
mpz_set_str(a, "10", 10);
printf("gets here a\n");
mpz_set_str(b, "20", 10);
printf("gets here b\n");
mpz_set_str(c, "30", 10);
printf("gets here c\n");
}
编译为:gcc -lm -lgmp -o segf segf.c
documentation for mpz_set_str
说:
5.2 Assignment Functions
These functions assign new values to already initialized integers (see Initializing Integers).
...
link 转到
5.1 Initialization Functions
The functions for integer arithmetic assume that all integer objects are initialized. You do that by calling the function mpz_init
. For example,
{
mpz_t integ;
mpz_init (integ);
…
mpz_add (integ, …);
…
mpz_sub (integ, …);
/* Unless the program is about to exit, do ... */
mpz_clear (integ);
}
As you can see, you can store new values any number of times, once an object is initialized.
您的代码没有初始化变量,因此 mpz_set_str
等赋值函数会产生垃圾。
任何人都知道为什么在第二次调用 mpz_set_str() 后以下会导致段错误?如何从 str 初始化两个以上的 gmp 整数?
#include <gmp.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
mpz_t a, b, c;
mpz_set_str(a, "10", 10);
printf("gets here a\n");
mpz_set_str(b, "20", 10);
printf("gets here b\n");
mpz_set_str(c, "30", 10);
printf("gets here c\n");
}
编译为:gcc -lm -lgmp -o segf segf.c
documentation for mpz_set_str
说:
5.2 Assignment Functions
These functions assign new values to already initialized integers (see Initializing Integers).
...
link 转到
5.1 Initialization Functions
The functions for integer arithmetic assume that all integer objects are initialized. You do that by calling the function
mpz_init
. For example,{ mpz_t integ; mpz_init (integ); … mpz_add (integ, …); … mpz_sub (integ, …); /* Unless the program is about to exit, do ... */ mpz_clear (integ); }
As you can see, you can store new values any number of times, once an object is initialized.
您的代码没有初始化变量,因此 mpz_set_str
等赋值函数会产生垃圾。