0

I've just downloaded and installed (following the site's instructions) the latest version of GMP (6.2.1) to use in my c++ projects. I read the tutorial and put together some simple code, but trying to set a variable using mpf_set crashes with a SIGSEGV. Here's my code (minimal reproducible example, not the actual code):

main.cpp:

#include "pi_gmp.h"

int main() {

    mpf_t result;

    mpf_set_default_prec(256);
    mpf_init(result);
    pi_gmp(result, 1E12);

    exit(0);

}

pi_gmp.cpp:

void pi_gmp(mpf_t result, unsigned long long precision) {

    mpf_set(result, 0);

}

I looked at the core dump:

Core was generated by `./main'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00007f5239129706 in __gmpf_set () from /usr/local/lib/libgmp.so.10

Which is of course not a function I wrote but a GMP lib function.

Some more info:

(gdb) x/i $pc
=> 0x7f5239129706 <__gmpf_set+6>:       movd   xmm0,DWORD PTR [rsi+0x4]
(gdb)
(gdb) info registers
rax            0x5                 5
rbx            0x0                 0
rcx            0x41                65
rdx            0x0                 0
rsi            0x0                 0
rdi            0x7ffd2fd62fc0      140725406019520
rbp            0x7ffd2fd62f90      0x7ffd2fd62f90
rsp            0x7ffd2fd62f78      0x7ffd2fd62f78
r8             0x7f5238c1b1f0      139991116263920
r9             0x55bc5a61feb0      94267458584240
r10            0x7f523911dac0      139991121517248
r11            0x7f5239129700      139991121565440
r12            0x7ffd2fd63108      140725406019848
r13            0x55bc58b93740      94267430745920
r14            0x55bc58b95d88      94267430755720
r15            0x7f52391f8040      139991122411584
rip            0x7f5239129706      0x7f5239129706 <__gmpf_set+6>
eflags         0x10206             [ PF IF RF ]
cs             0x33                51
ss             0x2b                43
ds             0x0                 0
es             0x0                 0
fs             0x0                 0
gs             0x0                 0

Does anyone know what could be the problem?

AGL
  • 47
  • 5

1 Answers1

0

mpf_set, function signature is void mpf_set (mpf_t rop, const mpf_t op) as mentioned in Assigning-Floats.

The function is expecting two gmp_f's as arguments, passing a (mpf, 0), the 0 gets treated as a gmp_f, which is a typedef to the __mpf_struct, In this case when accessed leads to a segmentation fault.

To pass an integer, you can use mpf_set_ui or mpf_set_si, which take in a unsigned long int and signed long int respectively as mentioned in comments by @273k

GMP Manual is a great place to get started.

SowmithK
  • 11
  • 3