首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用std::ptr::read in Rust时避免双重错误

使用std::ptr::read in Rust时避免双重错误
EN

Stack Overflow用户
提问于 2022-06-08 11:01:30
回答 1查看 190关注 0票数 1

我试图从指针中读取一个值,但是我总是得到一个double-free错误。你们知道怎么解决吗?我使用mem::forget来阻止空闲操作,但仍然得到了相同的结果。

代码语言:javascript
复制
use std::ptr;
use std::mem;

fn main() {
    let test = String::from("hello!");
    println!("{}", get_value_from_ptr(&test));
    println!("{}", get_value_from_ptr(&test));
}

fn get_value_from_ptr<T>(val: &T) -> T {
    let value = unsafe { ptr::read(val) };
    mem::forget(&value);
    value
}

错误:

代码语言:javascript
复制
   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.26s
     Running `target/debug/playground`
free(): double free detected in tcache 2
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11:     8 Aborted     
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-08 11:07:08

mem::forget()必须有自己的价值。如果您为它提供了一个引用,它将忘记引用--这是没有意义的,因为引用无论如何都没有Drop胶水。您必须使用mem::forget(value),而不是mem::forget(&value),但是如果您离开了value,就无法返回它。

你想做的根本是不可能的。如果一个值不实现Copy,就不能正确地复制它。即使只是ptr::read(),它也可能使原始值失效,即使您立即对其进行forget() (这件事还没有决定)。事后使用它是不可能的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72544574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档