+ 1
What is the number? why is the deleted *p output it?
Could you do me a favor? I learning pointers of C++,and tried it below. I using visual studio 2017. ¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨ #include<iostream> using namespace std; int main(){ int *p=new int; *p=9; delete p; cout << *p << endl; return 0; } ¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨ output ↓ -572662307 I assumed it occurs an error, but it output -572662307. Why is this number appeared? What's going on? I don't understand the process to output it. Please forgive me if I mistake grammar. Thank you.
4 odpowiedzi
+ 9
See here:
https://isocpp.org/wiki/faq/freestore-mgmt#delete-p-doesnt-delete-p
this is why you need to set the pointer to null 'after' you delete it. See code example (your code with added p = nullptr;)
https://code.sololearn.com/cJrQKYk9juCC/?ref=app
+ 1
well what would you expect the result to be?
This called undefined behaviour. As you have deleted the allocated memory for the pointer, this means the pointer could be pointing anywhere and could point to any value.
Basically don't do this. If your code doesn't know if pointer is pointing to valid data, you can check if it's a null pointer.
+ 1
@jay
Thank you for your answer!
I understood that I didn't realize it.
It's nothing, it needs to set null. I thought I finally realized!
Thank you very much for your answer, introduced me great web site, and coded to easy to understand. I'm glad to see the answer!
0
@Jared Bird
Thank you for your reply!
I'm sorry for ask you ambiguous question. I would like to just make sure that a deleted location to be left on the stack that I learnt in the tutorial.
I mistook the code(not use & but *), but it output the number. I wondered "why is the number appears? what does mean? It doesn't contain anything. Maybe it should occur an error?"
Umm... what did I respect...
Thank you very much!