Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when a "new" item has been deleted [duplicate]

Consider this program:

int main()
{
    struct test
    {
        test() { cout << "Hello\n"; }
        ~test() { cout << "Goodbye\n"; }

        void Speak() { cout << "I say!\n"; }
    };

    test* MyTest = new test;
    delete MyTest;

    MyTest->Speak();

    system("pause");
}

I was expecting a crash, but instead this happened:

Hello
Goodbye
I say!

I'm guessing this is because when memory is marked as deallocated it isn't physically wiped, and since the code references it straight away the object is still to be found there, wholly intact. The more allocations made before calling Speak() the more likely a crash.

Whatever the reason, this is a problem for my actual, threaded code. Given the above, how can I reliably tell if another thread has deleted an object that the current one wants to access?

like image 777
Artfunkel Avatar asked Nov 29 '22 17:11

Artfunkel


1 Answers

There is no platform-independent way of detecting this, without having the other thread(s) set the pointer to NULL after they've deleted the object, preferably inside a critical section, or equivalent.

The simple solution is: design your code so that this can't occur. Don't delete objects that might be needed by other threads. Clear up shared resource only once it's safe.

like image 98
Oliver Charlesworth Avatar answered Dec 10 '22 13:12

Oliver Charlesworth