0

Here is just code:

class TestApp {};

int main()
{
    TestApp* test= new TestApp;

    {
        std::shared_ptr<TestApp> testPtr (test);
    }

    delete test;
}

The question is this: why this application will not crash on "delete test"? And otherwise crash when I remove scope braces.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • it wrong in all case (with and without {}) because you 2 time call `delete test` - inside `~shared_ptr` destructor and explicit. if random it not crash, nothing say – RbMm Sep 17 '18 at 10:54
  • 10
    Undefined behavior is undefined. – melpomene Sep 17 '18 at 11:23
  • https://stackoverflow.com/questions/24771148/why-my-program-does-not-crash-if-destructor-is-called-twice, https://stackoverflow.com/questions/1930459/c-delete-it-deletes-my-objects-but-i-can-still-access-the-data – melpomene Sep 17 '18 at 11:30
  • @Ville-Valtteri - think that not exactly. in concrete example at your link - concrete destructor with concrete class can called any time without crash or ub, because here nothing that prevent call it multiple time. here task in 2 time call `delete test;` - free the memory which we already not own (after first delete) already 100% error – RbMm Sep 17 '18 at 11:58

1 Answers1

1

Because of undefined behavior. Trying to delete something that has already been deleted results in UB. Both of your use-cases are wrong and result in UB.

Chances are you are using g++ and receiving the following message:

Error in `./a.out': double free or corruption (fasttop): 0x00000000010eac20

If you were using Visual C++ compiler you would observe a comparable exception. Both with or without braces.

Ron
  • 14,674
  • 4
  • 34
  • 47