Search code examples
c++c++11shared-ptr

Program crashes on passing local variable address to shared pointer in c++


#include <iostream>
#include <memory>

using namespace std;

void func ()
{
    cout << "func\n";
    int localVariable = 10;
    int* p = new int;
    shared_ptr<int> ptr (&localVariable); 
    shared_ptr<int> ptr1 (new int); 
    shared_ptr<int> ptr2 (p); 
}

int main ()
{
    func();
    return 0;
}

I tried to pass heap allocated memory directly to shared_ptr and also tried some pointer which is allocated before, both compile and run successfully. But when i tried to pass local variable's address to shared_ptr, it crashed with following stack :

vidhu@~/Documents/CPP_Practice$ ./a.out func * Error in `./a.out': free(): invalid pointer: 0xbfc7f13c *

Aborted (core dumped)

Why this is happened ? I think deleting NULL pointer is safe but it is not good coding practice.


Solution

  • The shared_ptr will try to delete the localVariable when ptr goes out of scope. However, the localVariable is not heap allocated (via new), so it cannot be deleted (and is its memory is automatically managed by the stack).