Hello. Faced the problem of double calling the destructor (the destructor is called 2 times in a row for 1 and the same object).
Here is the calling code in main ():
CharRow row(4); CharRow row2(3); cin >> row; cin >> row2; CharRow temp = row - row2; CharRow is a class that contains a pointer to a string.
The problem occurs in the overloaded operator- ():
CharRow CharRow::operator- (CharRow& row2) { int row1Length = this->getRowCurrentLength(); int row2Length = row2.getRowCurrentLength(); CharRow tempRow(row1Length - row2Length); char source[row1Length]; for (int i = 0; i < row1Length; i++) { source[i] = this->ptr[i]; } char* tmpStr; tmpStr = strstr(source, row2.ptr); //if row2 is not substring for row1 if (tmpStr == NULL) { return *this; } strcpy(tmpStr, tmpStr + row2Length); for (int i = 0; i < row1Length - row2Length; i++) { tempRow.ptr[i] = source[i]; } return tempRow; } after line
return tempRow; The copy constructor is called:
CharRow::CharRow(const CharRow &obj){ this->ROW_MAX_LENGTH = obj.ROW_MAX_LENGTH; this->ptr = obj.ptr; } After the copy constructor, the destructor is called:
CharRow::~CharRow(){ //ptr = NULL; delete [] ptr; } And then this destructor is called again and the program crashes (because the destructor tries to delete the null pointer (as I understand it).
Help to reach a complete understanding of the problem and suggest how to get out of this situation correctly.