hsynydn
hsynydn

Reputation: 27

Why does shared_ptr not delete its memory?

int main(){

    int* iptr;
    {
    std::shared_ptr<int> sptr = std::make_shared<int>(12);
    iptr = sptr.get();
    }

    std::cout << *iptr;

    return 0;
}

Output

12

I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces. But output shows 12. Do I miss something?

Upvotes: 1

Views: 776

Answers (2)

eerorika
eerorika

Reputation: 238351

Why does shared_ptr not delete its memory?

shared_ptr does delete the memory that it owns when it is the last owner.

I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces.

You were expecting correctly.

But output shows 12. Do I miss something?

You're missing that accessing through invalid pointers results in undefined behaviour.

Upvotes: 7

Mikhail
Mikhail

Reputation: 21749

As properly pointed by eerorika, you are seeing undefined behavior here. Particularly, a dangling pointer. I.e. a pointer that points to a location with a deleted memory. Not only you can get arbitrary results, but your program might behave in a completely unexpected way.

I would strongly recommend using sanitizers to avoid such problems. Here is the output of the code compiled with -fsanitize=address (https://gcc.godbolt.org/z/Po3r9cvq7):

=================================================================
==1==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000000020 at pc 0x000000401439 bp 0x7fff630ed360 sp 0x7fff630ed358
READ of size 4 at 0x603000000020 thread T0
    #0 0x401438 in main /app/example.cpp:12
    #1 0x7fdd09b5b0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x40121d in _start (/app/output.s+0x40121d)

As you can see, it points out that you are trying to access a deleted memory. It also provides call stacks for operations that allocated and released the memory, which is very handy.

Upvotes: 5

Related Questions