Purin Lord Purin Lord - 1 month ago 26
C++ Question

double free or corruption with shared pointers

So the essence of my problem is this:

//Big.h
class Big{
public:
int a, b;
};

//Mini.h
class Big;
class Mini{
public:
Mini(float a, shared_ptr<Big> ptb):ma(a), me(-a), ptb(ptb){};
float ma, me;
shared_ptr<Big> ptb;
};

//main
int main(){
std::list<Mini> lm;
if(true){ //Or some sub function or rutin
Big big; big.a = 100; big.b = 200;
Mini derp(5, shared_ptr<Big>(&big));
lm.push_front(derp);
}
//Do something
};


Compiles fine but it gives a "double free or corruption" when exiting main (in the full program this is just a sub function)

I suspect the
shared_ptr
to
big
is being freed at some point and then again when exiting main, but I'm not sure and have no idea of how to fix it. Can someone please explain to me the reason of this error?

I red that I had to
NULL
the pointer to but I don't know where.
Or maybe I'm just using the wrong smart pointer or something like that?

Thanks

Answer

You're constructing a shared_ptr with a pointer to an existing object on the stack. Don't do that; that's not how shared_ptr is meant to be used. Ordinary stack objects should never be deleted or freed. The object it's pointing at is supposed to be on the heap, i.e. created using new or the equivalent.

The recommended way to create a shared_ptr is through make_shared:

auto p = make_shared<Big>();

or the old-fashioned way:

shared_ptr<Big> p(new Big);