Memory leak in the following program.
Brian Dean
elzoog4180 at yahoo.com
Thu Jan 24 17:02:53 UTC 2019
Since I am new to GMP, I don't know if this is a bug or if it's a result of my poor programming. However, here is the relevant code. If I compile this code using g++ and then run it, the amount of memory it will take up will increase gradually. Before, it was increasing quite rapidly (as in eating up about 2 GB every few seconds). I fixed it a little by rewriting the numdivs function to allocating the mpz_t variables at the beginning (rather than inside of the while loop).
Any help would be appreciated.
__________________#include <stdio.h>
#include <gmp.h>
const int numprimes = 1000;
static int primelist[numprimes];
void initprimelist() {
primelist[0] = 2;
primelist[1] = 3;
primelist[2] = 5;
primelist[3] = 7;
int test = 7;
int mod3int = 7 % 3;
int loc = 4;
while (loc < numprimes) {
if (mod3int == 1) {
test += 4;
mod3int = 2;
} else {
test += 2;
mod3int = 1;
}
int isprime = 1;
for (int i=0; i<loc; i++) {
int sqvar = primelist[i] * primelist[i];
if (test > (sqvar - 1)) {
if ((test % primelist[i]) == 0) {
isprime = 0;
}
}
}
if (isprime) {
primelist[loc] = test;
loc++;
}
}
}
unsigned long numdivs(mpz_t var) {
mpz_t tmpvar, modr, tmp;
mpz_init(modr);
mpz_init(tmp);
mpz_init_set(tmpvar, var);
unsigned long retval = 1;
int loc = 0;
while (mpz_cmp_ui(tmpvar, 1) > 0) {
unsigned int tmpdivs = 0;
mpz_mod_ui (modr, tmpvar, primelist[loc]);
while (mpz_cmp_ui(modr, 0) == 0) {
mpz_fdiv_q_ui (tmp, tmpvar, primelist[loc]);
mpz_set(tmpvar, tmp);
mpz_mod_ui (modr, tmpvar, primelist[loc]);
tmpdivs++;
}
retval *= (tmpdivs + 1);
loc++;
if (loc >= numprimes) {
return retval;
}
}
return retval;
}
int main() {
mpz_t six_t, test, var, tmp;
mpz_init(var);
mpz_init(tmp);
initprimelist();
// DivisorList *divlist = new DivisorList();
// Start with 13
mpz_init_set_ui (six_t, 6);
mpz_init_set_ui (test, 13);
unsigned long maxdivs = 1;
while (1) {
mpz_sub_ui (var, test, 1);
unsigned long ndivs = numdivs(var);
if (ndivs > maxdivs) {
mpz_out_str(stdout, 10, test);
printf(" %d\n", ndivs);
maxdivs = ndivs;
fflush(stdout);
}
mpz_add (tmp, test, six_t);
mpz_set(test, tmp);
while (mpz_probab_prime_p (test, 15) == 0) {
mpz_add (tmp, test, six_t);
mpz_set (test, tmp);
}
}
}
More information about the gmp-discuss
mailing list