I recently learned that if you preform a Box::leak(Box::new(value))
and receive a &'static
it becomes much easier to transfer values in between threads. I have one specific value which has to be accessible from different threads, however the problem is that I have to leak user login credentials, and as far as I'm aware if I do that, those credentials will not be cleared from the memory on application, exit. This makes me wonder if I shouldn't use this approach, or do modern operating systems have ways to stop malicious applications from collecting that data?
as far as I'm aware if I do that, those credentials will not be cleared from the memory on application, exit
The operating system will free all memory allocated by a process when that process terminates. This includes all leaked memory.
Even if this were not the case, what you are describing is not a memory safety issue. "Memory-safe" means something very specific, and it does not on its own include preventing access to sensitive information like passwords. Memory safety means that the following things are not possible:
The most succinct description of memory safety I can think of is "references to values always point at valid values" (though this may be a bit oversimplified).
To address why you're leaking memory in the first place: if all you're trying to do is share something between multiple threads, consider using Arc
instead. This implements a thread-safe reference counted smart pointer, which will free the held allocation when the last handle is dropped. Unless you're doing something really weird or where the overhead of atomic operations causes performance problems, you can almost always use Arc
instead of leaking.
As a side note, if you're concerned about the password persisting somewhere either on disk or after your program terminates, you want a "secure string." Implementations of secure strings will typically do two very important things: