谁能解释一下这种情况:为什么我在这个简单的代码中面临“双重自由”的问题?
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 detected *** ./test: double free or corruption (fasttop): 0x0868f008 ***...
当您输入Rreceive函数时,您将调用默认的复制构造函数,该构造函数不会对您的文本指针进行深层复制(换句话说,他只会将指针分配给新副本)。
退出Rreceive范围时,您可以从复制的实例中释放(文本),该实例将指向相同的内存地址。
退出主要功能范围时,您将尝试再次释放相同的内存地址。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句