I'm trying to write a class in c++ that creates a dynamic array and I'm encountering this problem
malloc: Incorrect checksum for freed object 0x7f9ff3c05aa8: probably modified after being freed.
Corrupt value: 0x2000000000000
I implemented three constructors (default, parametrized and copy) and I think this is the one causing problem because the code breaks here
CTable::CTable(string sName, int iTableLen)
{
s_name = sName;
cout<<"parametr: "<<s_name<<endl;
c_table = new int[iTableLen];
i_table_lenghth=iTableLen;
}
I also have to write a method changing the size of the array and returning true in case of the success and false in case of the failure. Maybe this method is causing the problem so this is how I implemented it.
bool CTable :: bSetNewSize(int iTableLen)
{
int size;
if(iTableLen < 0)
return false;
else if(iTableLen>=i_table_length)
size = i_table_length;
if(iTableLen < i_table_length)
size = iTableLen;
int *cTable;
cTable = new int[iTableLen];
for (int ii = 0; ii < size; ii++)
{
cTable[ii] = c_table[ii];
}
delete [] c_table;
c_table = cTable;
return true;
}
edit: The problem wasn't in any of those parts of the code. The method that was supposed to clone the object was causing the error. It happened because I allocated the object statically instead of dynamically. Here is the fixed method:
CTable* CTable::pcClone()
{
CTable *obj_clone;
obj_clone = new CTable(*this);
return obj_clone;
}
The problem is that you deleted c_table
in bSetNewSize()
and didn't set a new value to it, but used it in a later call. I Think you meant to put a c_table = cTable;
to the end of bSetNewSize()
function, as 500 - Internal Server Erro commented.
Also it is faster if you take the string
parameter as a const string&
to the constructor.
Edit: are you sure abaut
if(iTableLen >= 0)
return false;
This means that you actually resize only if iTableLen
is negative.
Didn't you mean
if(iTableLen < 0)
return false;