My question is:
int* x = new int; cout << x<<"\n"; int* p; cout << p <<"\n"; p = x; delete p; cout << p <<"\n";
I wrote this on my own to understand the pointer and understand (also get lost) the dynamic new and delete .
My Xcode can compile the program and return the following results:
0x100104250 0x0 0x100104250
I know that I can only call delete in dynamically allocated memory. However, I called delete in p in the above program and compiles.
Can anyone explain this to me? Why can I remove p ?
In addition, I found that the program has changed to the following:
int* x = new int; int* p; cout << p <<"\n"; delete p; cout << p <<"\n";
Then my Xcode compiles again and returns me:
0x0 0x0 Program ended with exit code: 0
and now I'm completely lost :(. Can someone explain this to me? Why could I remove p since it has nothing to do with x ?
Since Xcode compiles successfully, I assume that the above two programs are correct for the computer. However, I think this is again the statement "just deleting a call in dynamic allocated memory". Or, perhaps, I did not quite understand what a pointer is and what dynamic allocated memory is. I found this post when I searched on the Internet. But I donβt think it looks like my business.
Please help me.
I would like to ask one more question. The code here is about a binary search tree. From line 28-32, he deals with deleting the node with one child. Here I put this piece of code if the web link is not working.
else if (root-> left == NULL) {struct node * temp = root; root = root-> right; delete temp; }
It is these codes that prompt me to ask a question regarding the pointer. After the response given by this message. Is it correct to understand the code as follows?
I cannot first bind the parent node to the root with the right child of the root. and then remove the root of the node, since the subtree under the root of the node will also be deleted. So I have to create a temp pointer that points to the memory slot that root points to. Then I will connect the parent node with the root with the root to the right of root. and now I can safely remove the memory slot pointed to by βrootβ (ie the pace, since both point to the same memory). This way I free up memory and also keep the connection between parent and child. In addition, the pace is still present and still points to βthisβ memory slot. Should I set it to NULL after uninstall?
Thanks to everyone in advance.
Yaofeng