请告诉我为什么在堆栈中分配值没有导致双自由指针?谢谢。
#[test]
fn read_value_that_allocated_in_stack_is_no_problem() {
let origin = Value(1);
let copied = unsafe { std::ptr::read(&origin) };
assert_eq!(copied, Value(1));
assert_eq!(copied, origin);
}
/// test failed as expected: double free detected
#[test]
fn read_value_that_allocated_in_heap_will_result_in_double_free_problem() {
let origin = Box::new(Value(1));
let copied = unsafe { std::ptr::read(&origin) };
assert_eq!(copied, Box::new(Value(1)));
assert_eq!(copied, origin);
}
#[derive(Debug, PartialEq)]
struct Value<T>(T);
最佳答案
您使用的不安全方法只是创建引用值的按位副本。当您使用 Box
执行此操作时, 这不好,但对于像你的 Value
这样的东西包含整数的结构,可以将副本设为 Drop
整数没有副作用,而 drop
的 Box
访问全局分配器并更改状态。
如果您不理解我在此解释中使用的任何术语,请尝试搜索或在评论中提问。
https://stackoverflow.com/questions/71681279/