Yes, your code leaks memory. Your first guess at the behavior is correct. This code
Node *newNode;
for (int i = 0; i < 10; i++)
{
newNode = new Node(); // allocate memory 10 times in a loop...
}
delete newNode; // ... but free the memory only once!
allocates memory 10 times (the new
operator inside of the for
loop), but frees the memory used by only one of those objects (the delete
operator at the bottom). Naturally, this leaves the other 9 objects orphaned—the memory they consume is still allocated, but you now have no way of accessing it to free it. That is, of course, the very definition of a memory leak.
By contrast, this code
Node *newNode;
for (int i = 0; i < 10; i++)
{
newNode = new Node(); // allocate memory 10 times in a loop
delete newNode; // ... and free the memory each time
}
does not leak any memory, because there is one call to delete
for each call to new
. That's the big rule you have to keep in mind: if you don't match up each call to new
with a corresponding call to delete
, you will have a memory leak.
Or, perhaps the even better rule when you're working in C++ is never to use raw pointers in the first place. The C++ standard library provides a couple of great wrapper classes that implement the RAII idiom for pointers, which ensures that the objects pointed to get properly destroyed and therefore the memory that they consume gets freed. Start your research either in your favorite C++ book, or on Wikipedia.