I want to load 64 bit integers into gmp using the mpz_import method, I am aware I could achieve this by streaming the number out to a string and then using the assign operator but this is surely slower and sub-optimal.
This code runs fine on my 64bit MacBook running OSX, however fails with segmentation fault on a raspberry pi running Raspbian, 32 bit Ubuntu Server and 64bit Linux Mint, all fail on the mpz_import line.
Here's the code, compiled with gcc 4.7 g++ -std=c++11 -lgmp -lgmpxx main.cpp
#include <iostream>
#include <cstdint>
#include <gmp.h>
#include <gmpxx.h>
using namespace std;
int main()
{
mpz_t a;
int64_t b = 4;
mpz_import(a, 1, 1, sizeof(b), 0, 0, &b); //segfault on this line
mpz_class c(a);
cout << c << endl;
}
You need to mpz_init a before using it in mpz_import. From the documentation:
unsigned long a[20];
/* Initialize z and a */
mpz_import (z, 20, 1, sizeof(a[0]), 0, 0, a);