This is an odd little program you've thrown together, because usually you assign the memory that's been allocated to you to something, or you know... actually use it. In fact, I can't find any use cases of just allocating memory without actually assigning the pointer of that memory to anything, so most of what I say here is just going to be an educated guess.
That said, yes, this is a memory leak. You're allocating memory that you never deallocate, which is, the definition of a memory leak. Although you're using new, instead of the C version of malloc/alloc/calloc, you still have to eventually deallocate the memory using delete. The issue here arises in that because you never assign the pointer to anything, you can't specifically delete that block of memory. Moreover, because C++ does not have garbage collection, it won't automatically delete the block of memory for you when the scope of the for-loop ends as well. However, because you aren't assigning the block of memory to anything, C++ may or may not delete the memory block once you leave the scope anyway.
Essentially, because you did this in a weird way, I have no idea what the hell will happen. Here's a normal memory leak below:
- Code: Select all
int * p = new int; //Memory leak as it's never deallocated
pretentious wrote:Like even after termination of the program? Could you give an example?
Yes after the termination of the program, and already did.
pretentious wrote:I could have just as easily used malloc. I thought C++ worked the same way, just provided more abstraction
Essentially. There are bit more use cases in C++ and odd rules, but that's essentially right.