这个错误让我很生气......
Valgrinding 程序表明delete[]
in DataPackage::~DataPackage
(第 40 行)产生了问题。但是如果我删除它,程序就会泄漏。那么,如何修复它,我做错了什么?
主文件
#include "main.h" // currently includes DataPackage.h only
DataPackage aTestFunction(){
return DataPackage("hello",5);
}
int main(){
DataPackage pack1 = aTestFunction(), pack2 = aTestFunction();
pack1 = pack2;
for(unsigned int i = 0; i < pack1.getLength(); i++){
printf("0x%02x ", *(pack1.getData()+i)&0xff);
}
return 0;
}
数据包.cxx
#include "DataPackage.h" // defines only the class, and private members m_data (char*) and m_length (size_t), includes <cstdio> and <cstring>
DataPackage::DataPackage(){
m_data = NULL;
m_length = 0;
}
DataPackage::DataPackage(string data){
m_data = NULL;
setData(data.c_str(),data.length()+1);
}
DataPackage::DataPackage(const char *data, size_t length) {
m_data = NULL;
setData(data,length);
}
DataPackage::DataPackage(const DataPackage &pack) {
m_data = NULL;
setData(pack.m_data,pack.m_length);
}
const char* DataPackage::getData(){
return m_data;
}
void DataPackage::setData(const char *newdata,size_t newlength){
char* tmpdata = new char[newlength];
m_length = newlength;
memcpy(tmpdata,newdata,m_length);
delete[] m_data;
m_data = tmpdata;
}
size_t DataPackage::getLength(){
return m_length;
}
DataPackage::~DataPackage() {
delete[] m_data;
}