c - 使用 mpz_set_str 初始化两个以上的 mpz_t 会导致段错误

标签 c gmp

有人知道为什么第二次调用 mpz_set_str() 后会导致段错误吗?如何从 str 初始化两个以上的 gmp int?

#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).

...

链接转到

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 之类的赋值函数会产生垃圾。

关于c - 使用 mpz_set_str 初始化两个以上的 mpz_t 会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733035/

相关文章:

c - 为什么我的程序有内存泄漏检查错误?

c++ - 对大数进行因式分解

C++ mpz_class 和二进制文件

python - PyErr_CheckSignals 没有接收到信号

c - 以下警告的具体原因

c - 用于任意精度算术的 GCD 算法

c++ - GMP 使用什么算法进行素数场反转 (mpz_invert)?

python - 带有 mpz/mpfr 值的 numpy 数组

c - 为什么这个自定义网络服务会崩溃(用 C 语言编写)?

c - automake 的 subdir-objects 选项不起作用