Some understandings about New, Delete and Heap
First look at the following two simple programs:
the first:
// Visula C 6.0 environment
#include
void main ()
{
INT A = 3;
INT * P = new int;
P = & a;
COUT << * P << endl;
Delete P; / There is an error
}
second:
// Visual C 6.0 environment
#include
void main ()
{
INT A = 3;
INT * P = new int;
* p = a;
COUT << * P << endl;
Delete P;
}
One of the first programs have an error (generated .exe file, but running error)
The problem is in New and Delete, the stack is not very well understood.
The second program is correct.
Now let me find out:
INT * P = new int;
It is assigned a INT type space in Heap, and P is a pointer in the stack, which pointing to the int in Heap,
At the end of the program, the P pointer will release it, so you have to delete P at the end of the program. This is to release it.
The int allocated in Heap, whether it causes leakage of the HEAP area space, which is very serious.
In the first program:
P = & a;
It assigns the address of A to P, and P refers to a, not the int in Heap, later
Delete P;
This is to delete the P point to content, but at this point P pointing in the stack, and Delete cannot be used
The data of Stack is there.
In the second program:
* p = a;
This is just the INT pointing to P pointing to P, at this time, P is pointing to the INT in Heap,
So here
Delete P;
It is legal, there will be no errors.