Purin Lord Purin Lord - 6 months ago 67
C++ Question

double free or corruption with shared pointers

So the essence of my problem is this:

class Big{
int a, b;

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

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));
//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
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
the pointer to but I don't know where.
Or maybe I'm just using the wrong smart pointer or something like that?



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);