我正在尝试一个示例程序,我使用“malloc”分配内存并使用“free”取消分配内存......我知道使用“new”和“delete”是正确的方法,但我只是想要去理解……
我得到一个崩溃“分段违规”,但我不明白为什么......
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