-2

I was studying about creating a object with pointer using dynamic allocation. And i read that when an object is created once and its deleted twice,The heap memory gets corrupted. what does corrupted means? Is it similar to memory leak or is it something else?

int main()
{
    //consider my class name is sample
    sample *p= new sample;
    //some code 
    delete p;
    //some code
    delete p;
}

when i delete the p for the first time, the memory pointed by p gets cleared and returns safely to the heap. what happens the next time?

Arvind kr
  • 105
  • 1
  • 12

1 Answers1

1

The free store is a carefully managed system of free and allocated blocks, and new and delete do bookkeeping to keep everything in a consistent state. If you delete again, the system is likely to do the same bookkeeping on invalid data, and suddenly the free store is in an inconsistent state. This is known as "heap corruption".

Once that happens, anything you do with new or delete may have unpredictable results, which can include attempting to write outside the application's memory area, corrupting data, erroneously thinking there's no more memory, or overlapping allocation.

Safest bet is always set pointer to null after deleting it.

int *ptr = new int;
// do something
delete ptr;
ptr = null;
ravi
  • 10,474
  • 1
  • 12
  • 30
  • would suggest `nullptr` instead of `null`. It's definitely safe because delete of a nullptr is explicitely supported by the standard as having no effetct. – Christophe Nov 01 '14 at 12:00