c++ calling delete[] causes crash
I am allocating an array, and then when i call delete[] it causes the program to crash, the program works fine when I do not call delete. Here is my code
MyObject *myArray= new MyObject[numPoints];
delete[] myArray;
I'm super confused so any help would be appreciated
Also, when I debug I get the error message "HEAP CORRUPTION DETECTED: after Normal block (#48) at 0x000032E90. CRT d开发者_开发技巧etected that the application wrote to memory after end of heap buffer."
SOLUTION!: I was initializing the array with not enough space. For some reason I could still add things to the array but it would crash when the destructor was called.
My psychic debugging powers tell me that since MyObject
is doing dynamic allocation, you forgot to obey the rule of three....you're missing a copy constructor, copy assignment operator, or both. For one example see http://drdobbs.com/184401400
But since this is C++ you can solve all your problems by just using vector
instead. Please strongly consider that approach.
CRT detected that the application wrote to memory after end of heap buffer.
This usually means that you wrote past the end of the array.
Solution 1: find every single place you access the array, and put in an assert to validate that the index is greater than or equal to zero, and less than numPoints
.
Solution 2: replace MyObject *
with a std::vector
. (Do this one)
EDIT: When i uncomment everythign in the MYObject deconstructor the program does not crash. The deconstructor code is :
delete [] myPoints;
points is an array in MyObject.
Wait what, you allocate an array of MyObjects in your MyObject constructor? It's no small wonder you run out of heap if you allocate arrays recursively. At least if I understand correctly and you meant destructor.
If this is not the case, something fishy is still going on in your MyObject class. Either in the constructor or operator new [] or operator delete [].
精彩评论