0

I am learning shallow copy and deep copy so I wrote the below code myself that tries to deallocate the same memory block twice. But surprisingly the program isn't crashing. I don't know where it's going wrong.

#include<iostream>
using namespace std;

class Demo {
    private:
        int *data;
    public:
        Demo(int d): data {new int} {
            *data = d;
        }

        Demo(const Demo &src): data {src.data} {}

        ~Demo() {
            delete data;
        }
};

int main(void) {
    Demo d1(100);
    Demo d2 {d1};

    return 0;
}
  • 1
    Behavior on undefined behavior is invoked is undefined. The meaningless object may be optimized out. What is your compile and compilation option? – MikeCAT May 07 '21 at 13:26
  • What is that you're deallocating twice? By the way just because you do something that you shouldn't it doesn't mean the code should crash. – al3c May 07 '21 at 13:26
  • 1
    Here is an example: [crash without optimization](https://wandbox.org/permlink/h9TFFdUqd6rjAnjA) and [no crash with optimization](https://wandbox.org/permlink/PsfmprPTC6QaikT9) – MikeCAT May 07 '21 at 13:27
  • @al3c When the destructor gets called for the first time, it deallocates the memory block whose address is stored in the pointer variable ```d1.data```. When the destructor gets called for the second time, it tries to deallocate the memory block whose address is stored in the pointer variable ```d2.data```. But both the pointer variables refer to the same memory block so the second call to destructor must attempt to deallocate a random memory block and thus the program must crash but this isn't happening. – Gulshan Mishra May 07 '21 at 13:35
  • The key point to learn with this example is undefined behavior need not cause any type of crash or any kind of diagnostic report from your OS or ide. What's worse is your program may appear to work even though its considered broken. – drescherjm May 07 '21 at 13:46
  • @MikeCat I checked the links and noticed that the compiler flags are different. I will be grateful If you explain the difference between both the compiler flags. – Gulshan Mishra May 07 '21 at 13:53
  • 2
    when you rob a bank, you might not go to jail, nevertheless robbing a bank is forbidden and you have no guarantee that you not go to jail – 463035818_is_not_an_ai May 07 '21 at 13:59
  • 1
    See also [the hotel story](https://stackoverflow.com/a/6445794) -- crashing is never mandated by C++. – JaMiT May 07 '21 at 14:14

0 Answers0