edited*
I am learning about structs and pointers, and part of the assignment I am working on asked me to free up the space malloc'd for a struct pointer. The pointer is passed as an argument inside a function, and I was wondering if I can free the space inside the function? The pointer is declared in the main file, and all the function code is in a separate file. Below is my code, and when its tested Valgrind would say memory leak at the line where dict is declared in main. Any tips on how to approach this would be greatly appreciated.
the code that generates the struct pointer:
typedef struct dict_list {
char* key;
char* val;
struct dict_list* next;
} dict_list_t;
typedef struct dict {
dict_list_t* head;
size_t size;
} dict_t;
dict_t* dict_create () {
dict_t *ret = (dict_t *) malloc(sizeof(dict_t));
ret -> head = NULL;
ret -> size = 0;
return ret;
}
it is then called in the main file:
int main (int argc, char** argv) {
dict_t* dict = dict_create ();
the function that is called to remove the list as a whole
void dict_destroy (dict_t* dict) {
dict_list_t* el = dict->head;
dict_list_t* next_val;
while(el){
next_val = el->next;
dict_del(dict,el->key); //removes the key/value pair in dict if a matching key is found
el = next_val;
}
free(el);
free(dict->head);
free (dict);
}
this is the error message I get from Valgrind
HEAP SUMMARY:
==1801801== 16 bytes in 1 blocks are still reachable in loss record 1 of 2
==1801801== at 0x4C34F0B: malloc (vg_replace_malloc.c:307)
==1801801== by 0x400A77: dict_create (dict.c:18)
==1801801== by 0x400DEC: main (main.c:11)
CodePudding user response:
It's perfectly fine for a function to free
a pointer that was malloc
ed in some other function. However, it's extremely important to write a documentation comment that lets the person calling the function know that the pointer is being freed. We can't leave that stuff to chance in C.
In your current edit, we see that dict_t
has a pointer field head
, but we don't know if dict_clear
frees that pointer. That might be your problem.