Wednesday, 15 April 2015

c++ - Double-free error in execution after deleting pointer in deconstructor -



c++ - Double-free error in execution after deleting pointer in deconstructor -

i have class containing fellow member pointer dynamically allocated in constructor follows:

class record { public: record(unsigned short numbytes, char* bufrecord); ~record(); unsigned short size() {return m_numbytes;} private: unsigned short m_numbytes; char* m_bufrecord; }; record::record(unsigned short numbytes, char* bufrecord) { m_numbytes = numbytes; m_bufrecord = new char[numbytes]; for(unsigned short i=0; i<numbytes; i++) m_bufrecord[i] = bufrecord[i]; } record::~record() { delete m_bufrecord; }

it copies input buffer dynamically allocated fellow member buffer. proceed utilize class follows, in constructor of class:

class file { public: file(const char* filename); ~file(); unsigned int numrecords() {return m_records.size();} record getrecord(unsigned int numrecord) {return m_gdsrecords[numrecord];} private: std::ifstream m_file; std::vector<record> m_records; }; file::file(const char* filename) : m_file(filename, ios::in | ios::binary) { while(!m_file.eof()) { char bufnumbytes[2]; char* bufrecord; unsigned short numbytes; m_file.read(bufnumbytes, 2); numbytes = (bufnumbytes[0] << 8) + bufnumbytes[1] - 2; bufrecord = new char[numbytes]; m_file.read(bufrecord, numbytes); record record(numbytes, bufrecord); m_records.push_back(record); delete bufrecord; } }

however, when instantiate class, next error, seems state i'm double-freeing m_bufrecord:

*** error in `./a.out': double free or corruption (fasttop): 0x0000000001cb3280 ***

i'm guessing problem lies insertion of class containing pointer vector element, , destructor beingness called twice on same pointer i'm not sure how happens. doing wrong here?

this case of rule of three. if class needs free resources in destructor, needs declare re-create constructor (and re-create assignment operator), either re-create owned resource, manage shared ownership or prevent beingness copied.

c++ memory-management vector double-free

No comments:

Post a Comment