First, about free()
. If you need memory, you call malloc()
and it will give you a pointer that points to a block of memory that is yours now. The OS will (hopefully) take care that no one else will use this memory. But, as with all resources, be it sockets, open files or threads, you will have to relinquish this memory at one time. At the latest, when your application exits. Better, before that, ideally the moment you don't need it anymore. And that's what free()
is for. That pointer you got from malloc()
? Give it to free()
and you're telling the OS that you're done with this particular block of memory. This will allow other programs to reutilize the memory and keeps your memory footprint small. However, that means that you shouldn't use this memory yourself again. The mean thing is that using the memory anyway might not crash your application right away. That's why it's always a good idea to set a pointer to NULL
right after freeing it. That way, if you try to use this pointer again, it will crash directly, making it more obvious where the error is.
If you don't free memory you allocated, it's a memory leak. Especially if this happens periodically, it can be a real problem, because the longer your program runs, the more memory it consumes. Memory it doesn't use, but other programs might need. So always free your memory. Use tools like valgrind to check for leaks and other problems.
Now, to your function. I spotted one little error:
struct accListNode *temp = theList->head;
free(theList->head);
theList->head = temp; // Does nothing
theList->head->next = temp->next; // Potential crash
I think the first line should read
struct accListNode *temp = theList->head->next;
Otherwise, the third line does nothing (it's just the first line in reverse) and the fourth will sooner or later lead to a crash because you're accessing free'd memory.
Then, there's the second case, where there's only one element in the list. Are you sure you want to remove that element without first checking if it's actually the data that was requested to be removed?
And a small optimization in the last case:
for(cur = theList->head->next; cur != theList->tail; cur = cur->next)
You've already established that the data to remove isn't in the tail or head, so you don't need to check them again.
The rest is just stylistic:
if(theList->head == NULL)
return;
Even if it's only one line, it's good practice to put braces around it:
if(theList->head == NULL) {
return;
}
Also, you use struct accList
a lot. You can make a typedef like so:
typedef struct accList accList
It looks a little weird, but after that, you can replace all your struct accList
with just accList
. To better distinguish it from a variable name, I also recommend renaming it to AccList
.