Search code examples
c++heap-memorynew-operatordelete-operator

c++ what if I don't call 'delete' operator after creating a pointer to the heap?


I'm new to C++ and I just learned that when creating a new'ed pointer to heap memory, you have to delete it manually, for example:

int *a = new int;
...
delete a;

But, what if I don't delete it? Will it still take space on the heap forever (not literally forever, but you get the idea). I've created a few projects where I was just testing and messing around with it, and in some cases I didn't delete the pointer afterward. So, does it get delete'd automatically by Visual Studio (which I'm using)? Or, is it too late now and I can't do anything about it (freeing that space somehow)? Also, should I be worried (because I am)?


Solution

  • After a program terminates, the memory is freed by the operating system. The year is 2020, so there is no harm in those test applications you had since all modern operating systems handle it.

    That said, while the program was running, that memory remained allocated. This is bad because you are no longer using that memory and it is a waste of resources.