Search code examples
cmemory-leaksreallocbigint

Arithmetic with bigint in gmp `pointer being realloc'd was not allocated`


Following a previous question, I'm trying to do bigint arithmetic with gmp with the following main.c

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

int main (){
  mpz_t a, b, c;
  mpz_set_ui(a,0);
  mpz_set_ui(b,0);
  mpz_set_ui(c,0);

  mpz_set_str(a, "23", 10);
  mpz_set_str(b, "35", 10);
  printf("%s\n",mpz_get_str (NULL, 10, a));
  printf("%s\n",mpz_get_str (NULL, 10, b));
  printf("%s\n",mpz_get_str (NULL, 10, c));
  mpz_mul(c,a,b);
  printf("%s\n",mpz_get_str (NULL, 10, c));

//  mpz_t d;
//  mpz_mul(d,c,c);
  return 0;
}

If I write the command gcc so.c -lgmp && ./a.out I ge the output:

23
35
0
805

However if I uncomment the line 18 and 19 of main.c I get the following error:

a.out(93256,0x11207ce00) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort      ./a.out

What should I do to avoid the error?


Solution

  • You forgot to initialize your integers.

    mpz_init(a);
    mpz_init(b);
    mpz_init(c);
    

    As mpz_init initalizes and assignes zero to the integer so you do not need to mpz_set_ui(a,0); /* etc etc*/

    You can also use mpz_inits(a, b, c, NULL);