gpt4 book ai didi

c++ - 类破坏时的内存损坏(双重释放)

转载 作者:搜寻专家 更新时间:2023-10-31 00:33:36 24 4
gpt4 key购买 nike

谁能解释一下这种情况:为什么我在这段简单的代码中遇到“双重释放”问题?

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 范围时,您从复制的实例中释放(文本),它将指向相同的内存地址。

当退出 main 函数的范围时,您将尝试再次释放相同的内存地址。

关于c++ - 类破坏时的内存损坏(双重释放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com