Osamede Zhang wrote:
I just find i can't understand the code like this
int main()
{
int *p=new int;
//do something
delete p;
return 1;
}
I use new operator allocate some memory in the heap,now i don't need
it,but our process also need to be killed.The heap is in our process'
address space,so i think the os should release our heap when it kill
process,isn't it?
That is up to your operating system.
why i should delete it by myself?
You seem to be the victim of a common misconception, namely that delete
returns memory to the OS. This is not mandated by the standard, and in
fact, it is very often false: many implementations keep memory around for
future allocations by the same program; sometimes the decision whether to
return memory is based upon the size of the chunk. The reason that the
standard is vague about the interaction of delete and the execution
environment (OS) is that the C++ standard cannot legislate the OS to take
the memory back.
However, it is a good habit to delete everything that you new. It helps to
get into that habit. Consider for instance:
class Y {
// some stuff
};
int main ( void ) {
Y* p = new Y;
// do something
delete p;
}
Now it actually makes a tremendous difference whether you call delete p or
not: the destructor of *p is called in one case but not in the other. If
the class Y manages resourced like files, TCP connections or some other
stuff, you may have a resource leak even if the OS reclaims memory.
Is there have some problems if i don't delete 'p'?
In the case above and with an OS that reclaims memory from dead process
bodies: no, since the destructor of int is trivial. However, reread all the
qualifications and ifs in that statement and then put the delete p in just
to get into a good habit.
Best
Kai-Uwe Bux