Can we access the memory unreleased?

The question is about smart pointer. I define a custom smart pointer which does not implement Drop trait.In another function, I create an instance of it to do some work. After the function executed, the pointer itself is destroyed. However the memory allocated on heap is not released. Can I access these momery?

If the last pointer to a block of memory is destroyed, there’s no reliable way to access it anymore. You’ll need to save a copy of the pointer somewhere in order to access the memory later.

If you saved a copy of the raw pointer in a variable before destroying the smart pointer, and the heap memory being pointed to is never freed or has its destructors run then yes, it's safe to use. There is even a method on Box called Box::leak() which explicitly does this.

That's not to say it's a good idea though.

It'll be easy to shoot yourself in the foot if the smart pointer is used to wrap an object who's Drop impl is important for its functionality. Besides leaking memory and opening yourself up to unbounded memory growth (which can trigger an OOM), some other unpleasant side-effects are:

  • if it contains a lock guard the lock will never be released
  • a channel will never be closed
  • a file handle will never flush to disk or close
  • database connections will never be released back to the connection pool
  • reference-counted pointers will never be decremented
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.