Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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();
}

EDIT: Gurus, i am confused by many of the statements "it may crash or may not".. why isnt there a standard to say, this how we deal with a block of memory that is deleted using 'delete operator'..? Any inputs ?

like image 583
Vijay Angelo Avatar asked Jun 17 '09 10:06

Vijay Angelo


People also ask

What happens when you delete an object C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

How do you clear the memory of an object in C++?

Using the delete operator on an object deallocates its memory.


1 Answers

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

like image 51
Srekel Avatar answered Sep 29 '22 22:09

Srekel