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/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust(("Rust")) -.-> rust/ErrorHandlingandDebuggingGroup(["Error Handling and Debugging"]) 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! マクロは、パニックを発生させ、スタックをアンワインドし始めるために使用できます。アンワインド中、ランタイムは、そのすべてのオブジェクトのデストラクタを呼び出すことによって、スレッドが所有するすべてのリソースを解放することを担当します。

1 つのスレッドのみを持つプログラムを扱っているため、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 -->
<!-- Prevent REUSE from parsing the copyright statement in the sample code -->
$ 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 -->

まとめ

おめでとうございます!あなたは Panic! の実験を完了しました。あなたの技術を向上させるために、LabEx でさらに多くの実験を行って練習することができます。