c++ - Heap Corruption Detected - class with pointers -


the following code, results in assertation error. in addition, warning error message indicates heap corruption detected.

class {     int* a; // dynamic array of ints     a() {};     a(int size) {         = new int[size];      }     ~a() {         delete [] a;         = nullptr;     } }  *** in code somewhere *** int size = 5; temp = a(size); 

the cause of error is:
temp = a(size);
line calls:

  1. a's copy constructor, here: temp = a(size); the problem is, creates shallow copy, since uses default copy constructor, , have pointer in class, needs deep copy!
  2. a's parametrized constructor, here: a(size);
  3. a's destructor, delete our pointer created a temp , null it.

then when temp variable goes out of scope, destructor called again, , result in assertation fail.

solutions:

1. temp(size);
instead of temp = a(size);

this call parametrized constructor.
or
2. overwrite default copy constructor create deep copy!

another correction marco costa
better initialize a nullptr in default constructor.

another correction user4581301
destructor should check, if a nullptr, before deleting.

additional readings:
1. why aren't pointers initialized null default?
2. rule-of-three becomes rule-of-five c++11? suggested chad
3. scalar deleting destructor issue suggested chad


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -