使用std :: ptr ::在rust中阅读时双重错误

发布于 2025-02-05 10:10:43 字数 859 浏览 3 评论 0 原文

我正在尝试从指针中读取一个值,但我总是会收到双重错误。你们知道一种解决方法吗?我正在使用 mem ::忘记来阻止免费操作,但我仍然得到相同的结果。

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
}

错误:

   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     

i am trying to read a value from pointer but i always get a double-free error. Do you guys know a way to fix it? I am using mem::forget to block the free operation but i still get the same result.

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
}

Error:

   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     

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌吟 2025-02-12 10:10:43

mem :: nove()必须采用拥有的值。如果您为其提供参考,它将忘记参考 - 这是毫无意义的,因为无论如何都没有 drop 胶水。您必须 mem ::忘记(value)而不是 mem ::忘记(&amp; value),但是随后您移出 value ,您无法返回。

您要做的是从根本上不可能的。如果值不实现复制,则不能很好地复制一个值。即使您立即 nove> nove() it( ptr :: read()它也可能使原始值无效。 com/rust-lang/unsafe-code-guidelines/essument/307“ rel =“ nofollow noreferrer”>尚未确定)。之后使用它是一个非启动器。

mem::forget() must take an owned value. If you provide it with a reference, it'll forget the reference - which is meaningless since references do not have a Drop glue anyway. You'll have to mem::forget(value) and not mem::forget(&value), but then you move out of value and you cannot return it.

What you're trying to do is fundamentally impossible. You cannot duplicate a value soundly if it does not implement Copy. Even just ptr::read()ing it may invalidate the original value, even if you immediately forget() it (this is not decided yet). Using it after is a non-starter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文