有人可以解释一下这种情况吗:为什么我在这个简单的代码中面临“双重释放”问题?
void Rreceive (myclass){}
int main () {
myclass msg (1);
Rreceive(msg);
return 0;
}
其中 myclass
是:
class myclass
{
private:
HeaderType header;
byte * text;
public:
myclass(int ID);
~myclass();
HeaderType getHeader();
byte * getText();
};
myclass::myclass(int ID){
header.mID = ID;
text = (byte *)malloc (10);
memset (text, '.', 10);
}
myclass::~myclass(){
free (text);
}
HeaderType myclass::getHeader(){
return header;
}
byte * myclass::getText(){
return text;
}
并且 HeaderType 是:
typedef struct {
int mID;
}HeaderType;
错误是:*** glibc 检测到 *** ./test: 双重释放或损坏 (fasttop): 0x0868f008 ***...
最佳答案
当您进入 Rreceive 函数时,您将调用默认的复制构造函数,该构造函数不会对文本指针进行深层复制(换句话说,他只会将指针分配给新拷贝)。
退出 Rreceive 范围时,您从复制的实例中释放(文本),该实例将指向相同的内存地址。
退出主函数范围时,您将尝试再次释放相同的内存地址。
关于c++ - 类破坏时的内存损坏(双重释放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218886/