Search code examples
cgmp

Memory allocation error in GMP code


This one is for the math geeks ;)

I am writing a small C program to calculate say, the first 10 Fibonacci numbers usingn the GNU MP library. Here is my attempt:

#include "gmp.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


int main(int argc, char * argv[]){

    mpz_t a, b, c;

    mpz_init_set_ui(a,1); /*  a = 1  */
    mpz_init_set_ui(b,1); /*  b = 1  */

    for (int i=1; i <= 2 ; ++i){
        mpz_add(c,a,b); /* c = a + b */
        mpz_mul_ui(a,b,1);
        mpz_mul_ui(b,c,1);
    }

    mpz_out_str(stdout,10,c);
    printf ("\n");
    mpz_clear(a);
    mpz_clear(b);
    mpz_clear(c);

    return 1;
}

I have successfully compiled the code using gcc (version 7.2.1) with no errors using the command: gcc -o fibonacci fibonacci.c -g -lgmp -lm. However, this code has proven not too successful since when I run it I get the following error:

*** Error in `./fibonacci': realloc(): invalid pointer: 0x00000000004008bd ***

What am I doing wrong? Thanks


Solution

  • You haven't initialized variable c. Use this:

    mpz_init(c);
    

    Even if you don't want to set an initial value, you still have to initialize the variable to set values to it, otherwise the program will throw errors.

    Also, one helpful thing you can do when debugging GNU MP (and really anything else) is to go through and comment out lines one by one to locate the problem. I had this problem this morning and that's how I solved it.