Hi,
Please see the snippet bellow (playground).
I have function with a parameter as data_reader: Box<dyn Read> that make parameter static and I have another function with a password parameter.
As lifetime of static is during all the program run, I would try to zeroing password. I am not sure of memory management of rust. I need advice(s)
I imaged three approaches:
- Use mut &str. clear it after using. But in some step it become static
- Use mut &'static str. According my understanding because of static it will keep it in the same address in memory so if I zeroing the variable it's maybe better.
- I use explicit drop but. I can print it after. Due to the reference
Question:
- Do I really erase the memory with these approaches?
Thanks for advices
#![allow(unused)]
use std::io::{Read, BufReader};
fn main() {
// Question is: Do I really zeroing my memory ?
// Scenario 1,
let mut pwd:&str = "My secret password";
do_with_password(pwd);
pwd = "______________________________________";
println!("Scenario 1: {}",pwd);
// Scenario 2,
let mut pwd_x:&'static str = "My secret password";
do_with_password(pwd_x);
pwd_x = "______________________________________";
println!("Scenario 2: {}",pwd_x);
// Scenario 3,
let mut pwd_y:&str = "My secret password";
do_with_password(pwd_y);
pwd_y = "______________________________________";
drop(pwd_y);
println!("Scenario 3: {}",pwd_y);
}
// function doing a task using data reader as Box<dyn Read>
// so data_reader is implicit static
fn do_from_reader(data_reader: Box<dyn Read>) {
let mut buffered = BufReader::new(data_reader);
let mut dummy : Vec<u8> = Vec::new();
buffered.read_to_end(dummy.as_mut()).unwrap();
}
// function doing a task using a password and previous function so
// so password parameter should be static (explicit)
fn do_with_password(password : &'static str) {
let pwd = BufReader::new(password.as_bytes());
do_from_reader(Box::new(pwd));
}
Output:
Scenario 1: ______________________________________
Scenario 2: ______________________________________
Scenario 3: ______________________________________