I am a C beginner, and I am writing a very simple linked-list. I am wondering if there would be a memory leak in the following code:
void removeListEntry(struct tableEntry *symp, struct tableEntry *previous) {
if (symp->next = 0){
symbolList.tail = previous;
previous->next =0;
} else {
previous->next = symp->next;
symp->next = 0;
}
}
I am pretty sure if the pointer symp is not stored in another variable, there’s no way of accessing the list entry that was pointed by the pointer, thus I will have a memory leak.
In C, we use malloc() function to allocate memory space for a data structure, and I remember using new keyword to “dynamically” allocate memory in C++. What are the differences between allocating memory using malloc() and using new? Is there indeed a memory leak in my code?
I am curious about what is supposed to be happening in your code:
When would
symb->nextnot be zero? You aren’t doing anything ifsymbis empty as the head node would also be null.The confusing part is that you are appending
previoustosymbin the first if (which should always be the case) but in the next one you are appendingsymbtoprevious. What rationale is there for this second one, and in what case will it ever happen?As others have mentioned, if you allocate memory you need to free it, else you have a memory leak, as there is no garbage collector in C/C++, so every node that is going to be freed needs to be deallocated.
The
symb->next = 0is probably just a typo, as was pointed out, as that will always be true, and is a frequent bug. What I started to do to help catch this is to do:if (0 == symb->next), so if you did0=symb->nextthen you will get a compiler error.UPDATE:
As was pointed out in a comment, this function will always go to the ‘else’ clause, which may be expected behavior, actually.