I am trying to work with an array of mpz_t. I am passing two arrays, set_e1
and set_e2
to a function that will initialize them and fill them with mpz_t integers (that I call "signatures" in my code).
As the documentation states, we can free the memory allocated by mpz_init() using mpz_clear(). This works well when I clear inside the function, not if I use them after the function ( free() invalid pointer
). As everything gets allocated dynamically, I should be able to access it after the function.
I am not sure what I am doing wrong, and why mpz_clear works if I use it inside generate_training_sets
, but not if I use it in main
after calling generate_training_sets
.
Here is the code:
unsigned long generate_training_sets(mpz_t *set_e1, mpz_t *set_e2) {
char *samples_dir[2] = {SAMPLE_PATH_1, SAMPLE_PATH_2};
long nb_samples = 0;
char *filename = NULL;
attributes *ref_b = load_attributes("out_b");
attributes *ref_m = load_attributes("out_m");
for (size_t i = 0; i < 2; i++) {
nb_samples += d_nb_files(samples_dir[i]);
}
set_e1 = malloc(nb_samples * sizeof(mpz_t));
set_e2 = malloc(nb_samples * sizeof(mpz_t));
if (!set_e1 || !set_e2) {handle_error("malloc sets");}
for (size_t i = 0; i < nb_samples; i++) {
mpz_init2(set_e1[i], MAX_SIG_SIZE); // MAX_SIG_SIZE 6000
mpz_init2(set_e2[i], MAX_SIG_SIZE);
}
int j = 0;
for (size_t i = 0; i < 2; i++) {
mpz_t *sig_ex = malloc(sizeof(mpz_t));
mpz_t *sig_g = malloc(sizeof(mpz_t));
if (!sig_exports || !sig_5grams) handle_error("Malloc signatures");
mpz_init(*sig_ex);
mpz_init(*sig_g);
get_signature_ex("somepath", ref, *sig_ex);
get_signature_g("somepath", ref, *sig_g);
mpz_set(set_e1[j], *sig_ex);
mpz_set(set_e2[j], *sig_g);
}
ref_b->free(ref_b);
ref_m->free(ref_m);
return nb_samples;
}
int main(int argc, char const *argv[]) {
mpz_t *set_e1;
mpz_t *set_e2;
unsigned long nb_samples = 0;
nb_samples = generate_training_sets(set_e1, set_e2);
// for (size_t i = 0; i < nb_samples; i++) {
// print_sig(set_e1[i]); // doesn't work outside the function too for some reason?
// }
/* clear stuff */
for (size_t i = 0; i < nb_samples; i++) {
printf("%ld\n", i);
mpz_clear(set_e1[i]);
mpz_clear(set_e2[i]);
}
return 0;
}
A solution I found is initializing mpz_t
array before passing it to my function using:
mpz_t *set_1 = malloc(nb_samples * sizeof(mpz_t));
mpz_t *set_2 = malloc(nb_samples * sizeof(mpz_t));
This also allows to use mpz_clear
method on them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.