My question:
int* x = new int;
cout << x<<"\n";
int* p;
cout << p <<"\n";
p = x;
delete p;
cout << p <<"\n";
I wrote this purely by myself to understand the pointer and to understand (also get lost in) the dynamic new
and delete
.
My XCode can compile the program and return the following results:
0x100104250
0x0
0x100104250
I know I can only call delete on dynamically allocated memory.
However, I called delete on p
in the above program and it compiles.
Could anyone explain this to me?
Why could I delete p
?
Moreover, I found if the program changes to the following:
int* x = new int;
int* p;
cout << p <<"\n";
delete p;
cout << p <<"\n";
Then my Xcode again compiles and returns me:
0x0
0x0
Program ended with exit code: 0
and now, I got completely lost:(.
Could anyone please explain me this ?
Why I could delete p
since it has nothing to with x
?
Since Xcode compiles successfully, I assume the above two programs are correct for computer. However, I think it is again the statement of "only call delete on dynamic allocated memory". Or probably, I didn't fully understand what is pointer and what is dynamic allocated memory. I found this post when I searched online. But I don't think it is like my case.
Please help me out.
I would like to ask one more question. The code is here about binary search tree. From line 28 to 32, it deals with deleting a node with one child. I put this part of code here, in case the weblink does not work.
else if(root->left == NULL) { struct Node *temp = root; root = root->right; delete temp; }
It is these codes leading me ask the above the question regarding pointer. Following the answer given by this post. Is it correct to understand the code in the following way?
I cannot firstly link the parent node of root to right child of root. and then delete the root node, as the subtree beneath the root node will also be deleted. So I must create a temp pointer, pointing to the memory slot, which is pointed to by root. Then I link the parent node of root to right child of root. and now, I can safely delete the memory slot pointed by "root", (i.e. temp as they both point to the same memory). In this way, I release the memory and also keep the link between parent and children. In addition, the temp is still there and still points to "that" memory slot. Should I set it to NULL after deletion?
Thank you all again in advance.
Yaofeng