Yeah this is leaking memory. When you do:
newNode = new Node();
You are redefining the pointer to point to newly-allocated memory, in effect losing hold of a way by which to address the previously-pointed to memory in order to delete it.
So when you leave the loop, the newNode
pointer points to the last-allocated (tenth) memory/Node
. When you delete newNode
you are deleting only that memory. You no longer have a way by which to delete
the others.
As Zhi Wang pointed out, you can use some form of smart pointer (unique_ptr
or shared_ptr
in C++11 for example). These smart pointers are basically wrappers around regular pointers which have additional semantics which prevent this kind of leak. If you used one of these, the memory/objects would automatically be deallocated when they went out of scope (upon ending of the current iteration of the for
loop in that case).
However, I don't think this would solve your situation in this case. I doubt you want to delete
the 10 objects as soon as you create them. Rather, you probably want to store these objects in a container like a std::vector
or at the very least have an array of pointers pointing to each of these allocated instances. That way you will have the objects around (which I believe is what you want, since you're constructing them at all) and also have a way by which to remove them later.