I am trying a sample program where I allocate memory using "malloc" and de-allocate memory using "free"... I am aware of the fact that using "new" and "delete" is the proper way, however I just want to understand....
I get a crash "segmentation Violation", but I could not understand why...
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;
}
Output:
Using malloc to Construct Object
Object Constructed
Freeing Memory using "free"
Yes Object is Present, Defaulter is 10
Segmentation fault