I’m facing memory leak issues while running my C program. I’ve used Valgrind to detect memory leaks, but I’m confused about how to resolve them. My program appears to be functioning correctly, but Valgrind reports memory leaks.
I believe the memory leaks are coming from my main function. Although I know I should deallocate the h1
hashtable, I cannot do it outside the loop because it’s not defined there. If I attempt to do it inside the loop, it would be incorrect because I’m assigning h
to h1
, and if I deallocate h
, h1
would then be pointing to an undefined area.
int main(int argc, char *argv[]) {
for (int k = 1; k < argc; ++k) {
const char *t = argv[k];
printf("t%st", t);
}
hashtable *h1 = file_to_hashtable(argv[1]);
if (h1 == NULL) {
fprintf(stderr, "Error while creating hashtable n");
return EXIT_FAILURE;
}
for (int i = 2; i < argc; ++i) {
hashtable *h2 = file_to_hashtable(argv[i]);
if (h2 == NULL) {
hashtable_dispose(&h1);
fprintf(stderr, "Error while creating hashtable n");
return EXIT_FAILURE;
}
hashtable *h = merge_hashtables(h1, h2);
if (h == NULL) {
hashtable_dispose(&h1);
hashtable_dispose(&h2);
fprintf(stderr, "Error while creating hashtable n");
return EXIT_FAILURE;
}
hashtable_dispose(&h2);
h1 = h;
}
size_t k = 0;
while (k < POW2(h1->lbnslots)) {
cell *t = h1->hasharray[k];
while (t != NULL) {
const flword_occur *v = t->valref;
int file_count = 0;
for (int i = 1; i < argc; ++i) {
hashtable *ht = file_to_hashtable(argv[i]);
if (ht == NULL) {
hashtable_dispose(&h1);
fprintf(stderr, "Error while creating hashtable n");
return EXIT_FAILURE;
}
if (hashtable_search(ht, v->val) != NULL) {
file_count++;
}
hashtable_dispose(&ht);
}
if (file_count == 1) {
printf("n%st%dn", v->val, v->occur);
free(v->val);
free((void *) v);
}
t = t->next;
}
++k;
}
hashtable_dispose(&h1);
printf("n");
return EXIT_SUCCESS;
}
Faiza HADDADI is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.