Hi all,
I wrote a program in C++, it runs and sometimes crashes at runtime with the report:
inversesmw.x(1488) malloc: *** error for object 0x100100960: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
I don't know how to trace this actually. But one of my suspect is this function, which is a member function of class Vector<T>, simply appending a new number to the array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
template <class T>
class Vector
{
int n; //Length of array.
T* pdata; //Pointer to the first element.
public:
//Many other function here, and then this function:
void append(T Value)
{
T* newpdata = new T [n + 1];
for (int k = 0; k < n; k++)
{
*(newpdata + k) = *(pdata + k);
};
*(newpdata + n) = Value;
if (n > 0) delete [] pdata; pdata = newpdata;
n = n + 1;
};
Is it ok to delete pdata the assign it to newpdata like that? And would the allocate memory by new operator available after exiting from the function, or is it deleted together with all local variables?
Thank you all for reading and wish to have your helps.
I guess you didn't include all of your code. I don't see where you ever initialize pdata. If you have allocated pdata properly, you can delete where you have, but it is confusing because pdata has two uses: Pointer to the first element, and pointer to someother memory. Again: it's hard to know without the rest of the code.
When you allocate memory with new, it stays around until you delete it.
So I changed the memory where the object's data were in the function: completely delete the old memory, move the pointer to a new memory address where I had copied the old data plus a new element at the end to...
Yes, thanks for your suggestion, I should be more careful. Since I started C++ and have to write a long code immediately, a lot of mistakes in programing style there, hope it will be better over time :-)
Thanks, ne555. I found a carelessly deletion the pointer in the destructor without checking the state of the pointers. I hope that will keep the program safe now.