gpt4 book ai didi

c++ - 使用 'free' 释放内存时出现分段冲突

转载 作者:太空宇宙 更新时间:2023-11-04 15:49:58 26 4
gpt4 key购买 nike

我正在尝试一个示例程序,其中我使用“malloc”分配内存并使用“free”取消分配内存...我知道使用“new”和“delete”是正确的方法,但是我只是想明白....

我遇到了“segmentation Violation”崩溃,但我不明白为什么......

class Object{
public:
Object(){
this->def = 10;
std::cout<<"Object Constructed"<<std::endl;
}
~Object(){
std::cout<<"Object Destructed"<<std::endl;
}
void amIPresent(){
std::cout<<"Yes Object is Present, Defaulter is "<<this->def<<std::endl;
}
private:
int def;
};


int main(){
std::cout<<"Using malloc to Construct Object"<<std::endl;
Object *o = static_cast<Object*>(malloc(sizeof(Object)));
Object o2;
o = &o2;
std::cout<<"Freeing Memory using \"free\""<<std::endl;
o->amIPresent();
free(o);
return 0;
}

输出:

 Using malloc to Construct Object
Object Constructed
Freeing Memory using "free"
Yes Object is Present, Defaulter is 10
Segmentation fault

最佳答案

因为您正在重新分配 o 以指向不是使用 malloc 创建的对象。所以调用 free 是没有意义的。

关于c++ - 使用 'free' 释放内存时出现分段冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10228589/

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