c++ - Why a dynamically allocate object failed to be freed? -


i know should trivial question need find out why.

the following code compiled failed

a.out(93143) malloc: *** error object 0x7fff5af8293f: pointer being freed not allocated *** set breakpoint in malloc_error_break debug 

codes:

#include <iostream>  using namespace std;  class { };  class b {     private:         a;     public:         b(){a=*new a();}         ~b(){delete &a;} };  int main() {     b b; } 

according immediate comments, realized dynamically allocated object in "new" lost owner after assigning "a". if want object instead of pointer "a", best solution?

because member variable not pointer. you're not storing dynamically allocated object you're assigning copy of a a; , leaking dynamically allocated one.

change class b to:

class b {     private:         a* a;     public:         b(){a= new a();}         ~b(){delete a;} }; 

or better yet

class b {     private:         a;     public:         b() {}         ~b(){} }; 

in case really need dynamically allocated object, propose final solution using smart pointers (you'll need c++11 or boost this):

#include <memory> #include <iostream>  class { public:     a() { std::cout << "hi" << std::endl; }     ~a() { std::cout << "bye" << std::endl; } };  class b { public:     b(): a(new a()) {};     //~b() {} <-- destructor no longer needed, unique_ptr delete object private:     std::unique_ptr<a> a; };  int main(int argc, char* argv[]) {     b b; } 

you can see constructor , destructor called here.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -