I am attempting to create an overloaded + operator for my TurtleProgram class which stores a dynamically allocated array of strings. However, when the method returns, the destructor is called, and the delete operation inside throws an exception with the error "Invalid address specified to RtlValidateHeap".
Below are the overloaded operator definition, the destructor, the default constructor, the copy constructor, and the resize method definition used in the overloaded operator method.
I've done research on the error, but I haven't been able to find any issue related to mine.
// overloaded + operator
// postconditions: returns a new TurtleProgram object that is the sum of two TurtleProgam instruction arrays
TurtleProgram TurtleProgram::operator+(const TurtleProgram &that)
{
TurtleProgram returnTP;
returnTP.resize(this->size_ + that.size_);
for (int i = 0; i < this->size_ + that.size_; i++)
{
if (i < this->size_)
{
returnTP.instructions_[i] = this->instructions_[i];
}
else
{
returnTP.instructions_[i] = that.instructions_[i - this->size_];
}
}
return(returnTP);
}
// resize: resized the array to be of a new size
// preconditions: the new size must be a positive integer
// postconditions: the array is resized, and size is updated
void TurtleProgram::resize(int newSize)
{
string *temp = new string[newSize];
// iterate through, transferring the contents from the old array to the resized array, then setting any empty spaces to ""
for (int i = 0; i < newSize; i++)
{
if (i < size_)
{
temp[i] = instructions_[i];
}
else
{
temp[i] = "";
}
}
if (size_ != 0)
{
delete instructions_;
}
instructions_ = temp;
size_ = newSize;
}
// Default constructor: initializes as an empty array
// postconditions: a new TurtleProgram object is made with an empty array and a size of 0
TurtleProgram::TurtleProgram()
{
instructions_ = new string[0];
size_ = 0;
}
// Default destructor: deallocates instructions_ before destroying the object
// postconditions: the memory is released, and the object destroyed
TurtleProgram::~TurtleProgram()
{
if (size_ != 0)
{
delete instructions_;
}
}
TurtleProgram& TurtleProgram::operator=(const TurtleProgram &that)
{
resize(that.getLength());
for (int i = 0; i < size_; i++)
{
this->instructions_[i] = that.instructions_[i];
}
return(*this);
}
Can anyone spot what I am doing wrong / not understanding? Thanks in advance for any help, and sorry in advance for any posting errors. This is my first question!