I'm having an issue with some code that I'm writing; Whenever I delete the array that I've dynamically allocated my program crashes and throws an error that says "_BLOCK_TYPE_IS_VALID (phead- nblockuse)".
class Shape
{
protected:
unsigned int numberOfVertices;
glm::vec2 *vertexCoords; //openGL 2d vector..
public:
Shape();
virtual ~Shape() {}
}
class Rectangle : public Shape
{
protected:
unsigned int width;
unsigned int height;
void initVertexCoords();
public:
Rectangle();
Rectangle( unsigned int tempWidth, unsigned int tempHeight );
~Rectangle();
}
Rectangle::Rectangle( unsigned int tempWidth, unsigned int tempHeight )
{
width = tempWidth;
height = tempHeight;
initVertexCoords();
}
void Rectangle::initVertexCoords()
{
numberOfVertices = 4;
vertexCoords = new glm::vec2[ numberOfVertices ]; //Dynamic allocation..
vertexCoords[0].x = -width * 0.5f;
vertexCoords[0].y = -height * 0.5f;
vertexCoords[1].x = -width * 0.5f;
vertexCoords[1].y = height * 0.5f;
vertexCoords[2].x = width * 0.5f;
vertexCoords[2].y = height * 0.5f;
vertexCoords[3].x = width * 0.5f;
vertexCoords[3].y = -height * 0.5f;
}
Rectangle::~Rectangle()
{
delete [] vertexCoords; //freeing of dynamically allocated array..
//program doesn't crash when this destructor is empty!
}
So, a pointer to a 2D vector is created in Shape (the parent class), and the constructor of the subclass, Rectangle, dynamically allocates an array and stores the address of the first element in that pointer.
However, the program throws a runtime default exception [_BLOCK_TYPE_IS_VALID (phead- nblockuse)] when I try to delete that array in the Rectangle's destructor. When I remove the delete command from the destructor, the program compiles and runs fine. However, I'm concerned about the possibility of memory leaks; and I'd like to learn how to dynamically allocate objects and arrays of objects correctly. I've looked this up for about 2 hours now and I still haven't been able to find a solution.
I assumed that a call to 'new' dynamically allocates a certain amount of memory on the heap and would eventually require that memory to be freed by a call to 'delete'. It stands to reason that something that is allocated within the class constructor (or, in this case, in a class method which is called inside the constructor) should be freed within the class destructor..
I'm still new to C++ and programming in general, so there may be something very simple that I'm overlooking. Please let me know if there is a glaring error in my code that would cause this kind of error.