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?
You’re violating the “Rule of Five”: If you have any of the following, you probably need to write all the other four:
See:
Dynamic arrays are used so much that someone has already done all this hard work. Just change
bitsto astd::vector<char>and all the compiler-generated special member functions will just do the right thing. Ifbitspoints to memory owned by theRecordobject. If you’re intending to share memory between many objects, you can considershared_ptras suggested by Seth in the comments. But I suspect you aren’t wanting any sharing.