c++

Why is the below piece of code is not crashing, though I have deleted the object?


Consider:

class object
{
  public:
    void check()
    {
      std::cout << "I am doing OK..." << std::endl;
    }
};

int main()
{
  object *p = new object;
  p->check();
  delete p;
  p->check();
  delete p;
  p->check();
}

I am confused by many of the statements "it may crash or may not"... Why isn’t there a standard to say, this how we deal with a block of memory that is deleted using the 'delete operator'?


Solution

  • Because what it actually looks like after the compiler has had its way, is something like this:

    object::check( object* this )
    {
         // do stuff without using this
    }
    
    int main()
    {        
         object *p = new object;
         object::check( p );
         delete p;
         object::check( p );
         delete p;
         object::check( p );
     }
    

    Since you're not touching "this", you don't actually access any bad memory.

    Although, deleting p twice should be able to cause a crash:

    http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.2