I've found out that heap corruption error on delete[] is caused by writing somewhere where I didn't allocate anything (according to these posts: First post, Second post), the problem is though that even after trying to find the issue in this case, I am still unable to find it.
I am to create a simple database table where as a parameter of the function I get a row with data that has to correspond to the column data type.
So basically I created an array of pointers on other arrays (2d array) so that each array is row.
This is declaration for Table class:
class DLL_SPEC Table {
public:
void insert(Object** row);
void remove(int rowid);
Iterator* select();
void commit();
void close();
int getRowCount() const;
FieldObject** getFields() const;
int getFieldCount() const;
void setName(std::string name) { _nameOfTable = name; };
void setNumberOfFields(int numberOfFields) { _numberOfFields = numberOfFields; }
void setNumberOfRows(int numberOfRows) { _numberOfRows = numberOfRows; }
void setFields(FieldObject** fields) { _fields = fields; }
Iterator* select(Condition* condition) { throw 0; }
int findRowId(Condition* condition) { throw 0; }
void update(Condition* condition, std::function<void(Object**)> callback) { throw 0; }
private:
std::string _nameOfTable;
int _numberOfFields;
int _numberOfRows;
FieldObject** _fields;
Object*** _rowValues;
};
and here is the method for inserting that is causing the heap corruption error at delete[] tmpArray.
void Table::insert(Object** row)
{
Object*** tmpArray = new Object**[_numberOfRows + 1];
Object** checkedRow = new Object*[_numberOfFields];
// extend the array by 1 new row
for (size_t i = 0; i < _numberOfRows; i++)
{
tmpArray[i] = new Object*[_numberOfFields];
}
for (size_t i = 0; i < _numberOfRows; i++)
{
for (size_t j = 0; j < _numberOfFields; j++)
{
tmpArray[i][j] = _rowValues[i][j];
}
}
// check if the new row contains correct values for table
for (size_t i = 0; i < _numberOfFields; i++)
{
if (StringObject* v = dynamic_cast<StringObject*>(row[i]))
{
if (v->isType(_fields[i]->getType()))
{
checkedRow[i] = v;
}
continue;
}
if (IntObject* v = dynamic_cast<IntObject*>(row[i]))
{
if (v->isType(_fields[i]->getType()))
{
checkedRow[i] = v;
}
continue;
}
if (DoubleObject* v = dynamic_cast<DoubleObject*>(row[i]))
{
if (v->isType(_fields[i]->getType()))
{
checkedRow[i] = v;
}
continue;
}
throw std::invalid_argument("The fields of this table don't match with the data you want to enter.");
}
tmpArray[_numberOfRows + 1] = checkedRow;
_numberOfRows++;
_rowValues = tmpArray;
delete[] tmpArray;
delete[] checkedRow;
}