I'm currently learning libgmp and to that end I'm writing a small program which find prime factors. My program calls a function which fills an array with a varying amount of mpz_t integers, prime factors of a given number, which I need to return. I'm planning on setting the last element to NULL, so I know how many mpz_t integers the function found.
My problem is I'm getting double free errors with my array of pointers to mpz_t integers. I've written up some sample code illustrating my problem:
mpz_t *p = malloc(5*sizeof(mpz_t*));
gmp_printf("%Zd %Zd\n", p, p);
2 and 5 are printed to stdout, so allocation seems to be fine. But I'm getting the double free error below:
*** glibc detected *** ./lol: double free or corruption (out): 0x08e20020 ***
======= Backtrace: =========
I'm still getting totally used to pointers, and gcc gives no errors, however I'm fairly sure this is wrong and I should be doing something like
But that gives me a compiler error
test.c:8: error: incompatible type for argument 1 of â€˜__gmpz_init_set_uiâ€™
/usr/include/gmp.h:925: note: expected â€˜mpz_ptrâ€™ but argument is of type â€˜__mpz_structâ€™
Anyway, my questions are:
1. I'm sure I should be dereferencing the pointer in the mpz_init_set_ui() call, why is that wrong?
2. Is there a better way of doing this? Should I use a linked list?(I've not learned linked lists yet, I figure an array is best for this but if I'm really making things way more difficult, tell me)
3.Would it be better to create a struct with a pointer to my array and another variable with the amount of elements in my array and return a pointer to that instead?
The platform is linux 32-bit just in case that's relevant.
Here is the code I have just now, which I want to modify, I declare the array of mpz_t on the stack. But I want to make main() a function:
#define MAXFACTORS 100
mpz_t numToFactor, factor;
mpz_t result;/* used to pass return values from getPrimeFactor() */
mpz_init_set_str(numToFactor, "18 446 744 073 709 551 615 436 457 568", 10);
int pFLen = 0;
if(pFLen == MAXFACTORS)
puts("Ran out of space to store prime factors, quitting...");
mpz_divexact(factor, numToFactor, factor);
for(i = 0; i < pFLen; i++)
gmp_printf("%Zd ", primeFactors[i]);
Thanks in advance people, could you post the rest of the code?
以上就是double free error with pointer to array of mpz_t的详细内容，更多请关注web前端其它相关文章！