deltaray deltaray - 5 months ago 31
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_t sum;
unsigned int i = 0;

while (i < 4) {

printf ("\n");

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.


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