Rust 恐慌处理与内存安全

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习 Rust 中的 panic! 宏,它可用于引发恐慌并开始展开堆栈,导致程序报告恐慌消息并退出。运行时会通过调用对象的析构函数来释放线程拥有的所有资源。我们还将查看一个使用 panic! 宏处理除零错误的示例,并使用 Valgrind 验证它不会导致内存泄漏。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 进行编译和运行。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/ErrorHandlingandDebuggingGroup(["Error Handling and Debugging"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/DataTypesGroup -.-> rust/integer_types("Integer Types") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("Lifetime Specifiers") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("panic! Usage") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/integer_types -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/string_type -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/function_syntax -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/expressions_statements -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/lifetime_specifiers -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/method_syntax -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/panic_usage -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} rust/operator_overloading -.-> lab-488373{{"Rust 恐慌处理与内存安全"}} end

panic!

panic! 宏可用于引发恐慌并开始展开堆栈。在展开堆栈的过程中,运行时会通过调用线程所有对象的析构函数来释放该线程所 拥有 的所有资源。

由于我们处理的是单线程程序,panic! 将导致程序报告恐慌消息并退出。

// 整数除法 (/) 的重新实现
fn division(dividend: i32, divisor: i32) -> i32 {
    if divisor == 0 {
        // 除零操作会触发恐慌
        panic!("division by zero");
    } else {
        dividend / divisor
    }
}

// `main` 任务
fn main() {
    // 在堆上分配的整数
    let _x = Box::new(0i32);

    // 此操作将触发任务失败
    division(3, 0);

    println!("This point won't be reached!");

    // `_x` 此时应被销毁
}

让我们检查一下 panic! 不会导致内存泄漏。

<!-- REUSE-IgnoreStart -->
<!-- 防止 REUSE 解析示例代码中的版权声明 -->
$ rustc panic.rs && valgrind./panic
==4401== Memcheck, a memory error detector
==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4401== Command:./panic
==4401==
thread '<main>' panicked at 'division by zero', panic.rs:5
==4401==
==4401== HEAP SUMMARY:
==4401==     in use at exit: 0 bytes in 0 blocks
==4401==   total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated
==4401==
==4401== All heap blocks were freed -- no leaks are possible
==4401==
==4401== For counts of detected and suppressed errors, rerun with: -v
==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
<!-- REUSE-IgnoreEnd -->

总结

恭喜你!你已经完成了「恐慌!」实验。你可以在 LabEx 中练习更多实验来提升你的技能。