3 ms·
This doesn't actually work. It is possible to produce objects with 'static lifetime references at runtime. What &'static means is that whatever the reference i
by Tuna-Fish 8y ago
This doesn't actually work. It is possible to produce objects with 'static lifetime references at runtime.
What &'static means is that whatever the reference is pointing at will never be modified or go out of scope. One way to provide this is to put it in the read-only part of the executable, which is what literals do. Another is to use into_boxed_str() [1] and Box::leak() [2] to leak the string and thus make sure it will never be modified or freed. Neither function is unsafe, while Box::leak() is still only in nightly.
[1]: https://doc.rust-lang.org/std/string/struct.String.html#method.into_boxed_str https://doc.rust-lang.org/std/string/struct.String.html#meth...
[2]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak https://doc.rust-lang.org/std/boxed/struct.Box.html#method.l...
- michaelmior 8y agoGood clarification. Although it's at least likely to stop you from using user input accidentally. I think it's unlikely that someone would use either of the options above when constructing a string involving user input without knowing what they're doing.
- Paul-ish 8y agoThis does seem to be the case. Here is an example I was able to create: use std::io::stdin; fn main() { let mut s = String::new(); stdin().read_line(&mut s).expect("Did not enter a correct string"); let sql_example = format!("SELECT * FROM users WHERE username={}", s); let x = Box::new(sql_example); let static_ref: &'static str = Box::leak(x); println!("{}", static_ref) } Note the type on our variable "static_ref". It is a static str, meaning it could be an argument to the code in the blog post. No "unsafe" blocks either. When I run it Input: ' OR '1'='1 Output: SELECT * FROM users WHERE username=' OR '1'='1 The technique might be still useful if it was only allowed in debug builds to reduce boilerplate during debugging in a system that tried to use types to solve the issue.