I am trying to get the binary representation of a big integer in GMP. I am storing 1's and 0's in an array called expBinary. I use malloc to allocate a memory of size of "int", then use realloc to increase this memory whenever a new bit is added. The conversion is running perfectly without any issues, but when I try to allocate any more memory using malloc after the while loop, it is giving me segmentation fault when I call the same code a second time, first time it gives me no segmentation fault. I have checked and the "expBinary" is not storing anything out of bounds, I have given the code below
int binarySize = 0;                                                        
int * expBinary = malloc(sizeof(int));                                 
int i = 0;                                                                  
// Run until exp == 0                                                       
while(mpz_cmp_ui(exp,0) != 0)                                               
{                                                                           
    binarySize++;                                                           
    expBinary = (int*) realloc(expBinary,(binarySize));                     
    // Getting LSB of exp                                                   
    if(mpz_even_p(exp) != 0)                                                
        expBinary[i] = 0;                                                   
    else                                                                    
        expBinary[i] = 1;                                                                                                                                 
    // Incrmenting variables                                                
    i++;                                                                    
    // Dividing exponent by 2                                               
    mpz_tdiv_q_ui(exp,exp,2);                                               
}                                                                           
// This line is giving error
int * temp = malloc(sizeof(int));
 
    