1

I'm trying to do a Phonehandler system for a class I'm taking, The task specifies that we use a pointer to pointer for the Phone objects in the Phonehandler-class, and that the array to store Phones has a size of two phones from the start and that it can be expanded later. My relevant(?) code is as follow:

PhoneHandler.h

Phone **phones;

PhoneHandler.cpp (constructor)

PhoneHandler::PhoneHandler()
{
this->phones = new Phone*;
*phones = new Phone[2];
}

My code includes some more things than this, but I have not written "new" at any other place so the memoryleaks are allocated in the constructor. I've made a destructor as followed:

PhoneHandler.cpp (destructor)

PhoneHandler::~PhoneHandler()
{
delete[] phones;
delete phones
}

But it's crashing at the first line in the destructor. So I need help with ether the constructor or the destructor, maybe both. Feel free to ask me for more code if it's necessary, but I think that the problem is somewhere in this code. Thanks

Adam
  • 11
  • 2
  • 4
    `delete[] *phones;` to be coherent with constructor. – Jarod42 Feb 04 '16 at 18:11
  • BTW, Don't forget rule of 5/3/0 too. (copy/move/assignment). – Jarod42 Feb 04 '16 at 18:12
  • 2
    Don't try to be a [Three star programmer](http://c2.com/cgi/wiki?ThreeStarProgrammer). The extra indirection is useless and hurtful (as you see), and dynamically allocated arrays are just bad practice. There's `std::vector`. – LogicStuff Feb 04 '16 at 18:17
  • You delete `phones` twice. You, obviously, don't allocate `phones` twice. (Because `phones` has a value that cannot have been returned from two different allocation calls.) – David Schwartz Feb 04 '16 at 18:47
  • If I only have delete[] *phones I'm getting "_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" as a error message. But I still have memoryleaks – Adam Feb 04 '16 at 19:56

1 Answers1

0

delete [] phomes wont lead to any crash.

delete phomes is causing the crash.

Santhosh Kumar
  • 167
  • 2
  • 12
  • If I only have delete[] phones, it gives me "Heap corruption detected" as error message instead but I still have the memoryleaks – Adam Feb 04 '16 at 19:54
  • 1
    `delete [] phones` is UB as `phones` is allocated by `new` and not `new[]` – Jarod42 Feb 04 '16 at 23:47