I am here stuck with a question in my C++ book with the following:
"What does the use of new require you to also call delete?"
Maybe you have an answer for that?
I am here stuck with a question in my C++ book with the following:
"What does the use of new require you to also call delete?"
Maybe you have an answer for that?
Because that is the way C++ is designed & that is the intended behavior.
The intention was to provide a memory allocation which you demand and own till you reliquish it explicitly.
new
gives you a dynamic memory allocation(on heap) which will continue to exist and you own it untill you explicitly deallocate it by calling delete
.
Failing to call a delete
on a new
ed buffer will lead to Undefined Behaviors usually in the form of. 1 memory leaks.
delete
, and there are cases (e.g. a singleton) where you don't want to call delete
on new
ed memory. –
Phago when you do a new
, OS allocates the memory to the pointer you are assigning it. After your usage is completed you may not require it anymore. But the memory is still marked as "being used" by OS.
Now, when the pointer is declared in a scope of a function or any other block (of {}
), it will be deleted (only pointer will be removed) when the execution of the block is over. In such cases the memory that was allocated using new
is remained marked "being used" by OS and is not allocated to any other pointer that calls new
or to a variable. This causes an orphan block of memory in RAM, that will never be used because its pointer was removed from memory but it will occupy a memory block.
This is called a memory leak. A few of such blocks may make your application unstable as well.
You use delete
to free such memory blocks and relieve the OS so that it can be used well for other requests
There is no Garbage Collector in C++, and therefore you are responsible for deallocating the allocated memory. Anyway, the operating system "knows" what memory your program allocated. So when your program exits, the operating system is again responsible for the memory. But if you have a long running C++ program and never call delete noone will help you to get rid of your garbage.
delete
goes beyond simple memory management; it also calls the destructor. Even with a garbage collector, it's often necessary to use delete
. –
Phago Calling new has allocated memory for the object and it has also arranged for the constructor of that object to be executed.
You could free the memory by calling free(), but you should actually use delete to free memory allocated by new, since this will also cause the objects destructor to be executed.
© 2022 - 2024 — McMap. All rights reserved.