deltaray deltaray - 1 month ago 13
Linux Question

How to assign a float value using GMP library in C?

I'm trying to learn how to use the GMP library in C by just writing a simple program to add some floating point numbers together, but at runtime it complains:

GNU MP: Cannot allocate memory (size=140735132293330)
Aborted (core dumped)


Here is the code:

#include <gmp.h>
#include <stdio.h>

int main(){
mpf_set_default_prec(64);

mpf_t sum;
mpf_init(sum);
mpf_set_ui(sum,0);
unsigned int i = 0;

while (i < 4) {
mpf_add_ui(sum,sum,i);
i++;
}

mpf_out_str(stdout,10,sum);
printf ("\n");
mpf_clear(sum);
}


I was able to do this with just the GMP mpz functions without issue, but when I try this with floats I'm stuck. The documentation doesn't really show any real examples for float functions so maybe I'm initializing or assigning the values incorrectly.

Answer

From the documentation,

it is a good idea to include stdio.h before gmp.h, since that will allow gmp.h to define prototypes for these functions

This way you get an error because you are calling the function with the wrong number of arguments. The reason you are not getting any warning for the lack of declaration is because mpf_out_str is a macro, defined in gmp.h which on your machine is installed in /usr/include and thus considered a system header, so the warning is disabled (use -Wsystem-headers to see it). This feels like a misfeature in gcc...

Comments