我正在尝试一个示例程序,其中我使用“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/