I have a class 'Record' as follows:
class Record {
private:
char *bits;
char* GetBits ();
void SetBits (char *bits);
void CopyBits(char *bits, int b_len);
public:
Record ();
~Record();
}
I have an array of Record objects as follows:
Record *recBuffer = new (std::nothrow)Record[RECORD_SIZE];
Assume that the recBuffer has been filled with values. When I print them, they are fine. What could be the problem with the following code?
Record *newPtr = new (std::nothrow) Record[2*RECORD_SIZE];
if (NULL == newPtr) {
return;
}
//copy everything
for (int i = 0; i < RECORD_SIZE; i++) {
newPtr[i] = recBuffer[i];
}
delete[] recBuffer;
recBuffer = newPtr;
When I try printing the values of recBuffer till RECORD_SIZE, the first few values are corrupted and then there is a segfault finally!
So, I am updating the post with an answer by Ben: So, if you copy a Record (copying the bits pointer), (newPtr[i] = recBuffer[i]) they both will call delete[] with the same pointer. See a problem?