My question was why the code goes an endless loop when I execute the commented delete line down there. I figured it out while typing this because it is deleting the whole node, not the pointer itself (am I right?). |
You're right.
delete
doesn't destroy the pointer. It destroys the thing that the pointer points to. You don't want to do
delete temp;
on line 30 because then you'll destroy the node that you just inserted and
last
will be dangling which will lead to problems on the next iteration when you try to access the node that no longer exists. For you it happened to lead to an infinite loop but it's technically
undefined behaviour so there are no guarantees what will happen.
But is it causing a memory leak ... |
Yes. But you probably want to do the clean up (with
delete
) in a separate function when you're done using the linked list (if you wrote a LinkedList class this would normally be done in the destructor).
If you ever removed nodes before you're done using the linked list then you would also want to use
delete
to destroy those nodes.
... after the process is done? |
The operating system will clean up all memory when the process has ended.
I read that I don't have to use smart pointers with linked lists (I still don't know how to use them or what's they actually). They say it makes things more complex. |
Smart pointers are tools. You never
have to use them but they can often help you write better code where you don't have to worry too much about memory leaks.
Note that when people talk about "smart pointers" I think they primarily think about std::unique_ptr.
The other thing is, is it OK to use nullptr instead of NULL while coding linked lists? I read that in modern C++, it's solving some problems. But can it cause different problems here? |
It's recommended to use nullptr in C++ but it's not a big deal. It has some small advantages that you probably won't notice very often but there are no downsides as far as I am aware so why not use it.