I have created an array of pointers. I have used some of them as roots for singly linked lists.
The size of lgroup
(the array of pointers) is 10
and j
can get up to 10
as well. I malloc every lptr
like this:
lgroup[i].lptr[j] = (node *) malloc (sizeof(node));
and if I'm not going to use it I set curr = lgroup[i].jptr[j];
and curr->next = NULL;
.
Otherwise I just start using malloc
on every curr->next
and then I do curr = curr->next;
. When I don't want to add any more nodes to a list I just put curr->next = NULL;
and move on to the next lptr
. Pretty standard stuff.
At the end of my program I want to free
all of the memory that I have claimed for my lists. This is how I try to do it:
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (lgroup[i].lptr[j] == NULL) {
free(lgroup[i].lptr[j]);
continue;
} else {
curr = lgroup[i].lptr[j];
while(curr->next != NULL) {
curr2 = curr->next;
free(curr);
curr = curr2;
}
}
}
}
The thing is that I ended up with this code after a lot of trial and error and a lot of messages of "double freeing" and other stuff like that, so I'm not completely sure if it actually frees all the memory that I have claimed or that it just happens to compile and run without error but not doing all the things I want it to. I tried to run it on gdb but I really can't understand a lot of things by looking at memory addresses so I was curious if there is a way to check if it works as I expected or if I'm doomed to do it using pen and paper and running the code in my head. If it happens to actually do what it was designed for, would there be an easier and cleaner way to achieve the same results?
Thank you in advance and if you need any clarification don't hesitate to ask for it in the comments.