For some reason it works for me (I use DevC ++ 5.11):

int* a=new int(13); cout<<a<<endl; //0x635800 cout<<*a<<endl; //13 delete a; *a=123; (*a)*=2; cout<<a<<endl; //0x635800 cout<<*a<<endl; //246 

enter image description here

After freeing the memory cell pointed to by a , judging by the address, a new value was added to it, which can even be extracted, multiplied and the result placed in the same cell. Displays what was expected: 246. It says that "you can not do this": https://ru.stackoverflow.com/a/564989/279581 Why, if everything works? What does delete a; ?

    3 answers 3

    It simply marks the memory as free .

    What did you think? :)

    So you just write to an unallocated memory, read from it. Everything is working. But no one guarantees that this memory will not be overwritten, overwritten, or that you will not crash your memory manager with your own record after hitting the service records.

    Undefined behavior - it is so vague ....

    You see, you can cross the road at a red light. You can go over it blindfolded and plugged ears. And you will do it perfectly ... for the time being.

    And the fact that after several transitions you remained alive and healthy - is there any reason to say that “you can switch to red, I checked!”?

      C ++ is an adult language. He formulates rules for you, and it is your responsibility to follow these rules. Unlike other languages, C ++ will not check whether you are following the rules or not, it considers that you yourself are able to provide this.

      If you follow the rules, everything will work correctly. If not - there are no guarantees, maybe, maybe, maybe not, anything can go wrong at any moment. But you are an adult developer, do you understand everything?


      Here is Eric Lippert’s answer (one of the former leading developers of the C # language) to a similar question: https://stackoverflow.com/a/6445794/276994

      • +1 to favorite quotes - isnullxbh

      The behavior of your code is not formally defined . This means that anything can happen. Including it is possible that the code will supposedly "work." The fact that in your particular experiment the code "worked" does not contradict the fact that it is impossible to do this.