首页 > 解决方案 > 为什么使用 GMP 时出现分段错误?

问题描述

我正在使用GMP。我的程序可以成功构建,但运行失败。以下是错误的事情:

a=1231231231231231
res^n != a
Segment fault

我程序中的所有代码都是:

#include <gmp.h>
#include <stdio.h>
int main()
{
    mpz_t a,res;
    unsigned long int n = 123;

    char str1[] = "1231231231231231";
    mpz_init_set_str(a, str1, 10);
    gmp_printf("a=%Zd\n",a);


    mpz_init(res);

    if(mpz_root(res, a, n)){
        printf("res^n == a\n");
    }
    else{
        printf("res^n != a\n");
    }

    mpz_clears(a,res);
    return 0;
}

标签: cgmp

解决方案


你必须像这样调用 mpz_clears() :

mpz_clears(a,res, NULL);

这是文档中的内容:

Function: void mpz_clears (mpz_t x, ...)

    Free the space occupied by a NULL-terminated list of mpz_t variables. 

推荐阅读