AtomicPtr paradigm and memory leak

I have references to structs inside an AtomicPtr. I constantly reference them and make method invocations. This is the pattern of access:

let value = aptr.load(Ordering::SeqCst);
let value = unsafe { Box::from_raw(value) };
// do some stuff

I have to call forget() else bad things happen. But if I call forget() I seem to be leaking memory big time. Has anyone encountered this? Thanks in advance.

Are you doing this concurrently? A Box is a unique owner, like an owning &mut, so there may be some deeper unsoundness.

Ignoring aliasing concerns, I would expect a 1-to-1 correspondence between every Box::new + Box::into_raw and Box::from_raw + dropped (not forget). I.e. a manually tracked C-style malloc/free pattern.

If you have no way of ensuring no one else is holding a pointer to an object at any given point, leaking may be the only sound thing to do.


You don't have to use Box::from_raw if you just want to access the value. You can do that using the raw pointer directly.

1 Like

High concurrency with async tasks. Is there any tool that allows me to track which entities are taking most memory. For instance in Java I could take a heap dump and load it up in a profiler (for eg.Yourkit) and pin point which are the objects that consume most memory. Any such for Rust?

You're basically guaranteed to have undefined behavior if you're creating multiple Boxs from the same raw pointer concurrently. You should probably be using a Mutex or RwLock instead of AtomicPtr

The memory leaks are likely the old Box allocations being replaced by a new one in your AtomicPtr without being dropped.

1 Like

You shouldn't ever use mem::forget(). Patterns using it are often unreliable and dangerous. Everything that mem::forget() does can be safer using other methods or features.

To just access the pointer, use unsafe { ptr.as_mut().unwrap() } instead of from_raw and forget.

For other cases where you actually must forget a value later, wrap it in ManuallyDrop. That is safe, unlike forget that creates double free vulnerabilities if something panics before the necessary forget.

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.