C++ Heap Memory Question regarding Delete
Quick question:
When I call delete, it returns that object's memory to the heap, right?
That being true, then when a program exits, then is delete called for every heap allocation made in the program, or does this need to be done manually (via a linked list or just keeping track of the pointers)?
Re: C++ Heap Memory Question regarding Delete
You should call “delete” for every “new” call.
Code:
int v = new int;
//...
delete v;
If you allocate an array then you must call “delete[]”. “[]” guarantees the object’s destructor is called for each object in array before actual deletion.
The memory allocated for application is returned to the system once the application is exited, whether the memory was release with “delete” or not.
Re: C++ Heap Memory Question regarding Delete
Quote:
Originally Posted by nevolved
after the program exits everything is given back to the heap that was allocated during that program
Wrong. This is not true for all operating systems.
Whatever is allocated with "new" must be deallocated with "delete", otherwise the program has a memory leak.
Regards,
Paul McKenzie
Re: C++ Heap Memory Question regarding Delete
Quote:
Originally Posted by zdf
The memory allocated for application is returned to the system once the application is exited
See my reply. This is not true for all operating systems.
Regards,
Paul McKenzie
Re: C++ Heap Memory Question regarding Delete
Quote:
Originally Posted by Paul McKenzie
See my reply. This is not true for all operating systems.
Could you please give us an example?
Re: C++ Heap Memory Question regarding Delete
Quote:
Originally Posted by zdf
Could you please give us an example?
Example - AmigaOS. There may be more examples.
The problem is - what if this application is kept running? What if the application being made is an OS (leaking memory)? What if the application is leaking so much that it itself is not able to get the requested allocation?
Saying the OS will acquire it back, makes it look very-simple-to-ignore-bug. But it is not!
enigma - what you are assuming happens with applications running with a garbage collector. C#/Java applications fall into that category but C++ does not.
For more information refer this FAQ - What is the difference between malloc/free and new/delete?.
Hope it helps.
Re: C++ Heap Memory Question regarding Delete
Quote:
Originally Posted by zdf
Could you please give us an example?
Good old MSDOS -- the OS that practically a majority of PC's were running before Windows 95 came along.
Regards,
Paul McKenzie