book icon indicating copy to clipboard operation
book copied to clipboard

19.1 has an unsound example and does not explain it

Open nico-abram opened this issue 3 years ago • 1 comments

  • [X] I have checked the latest main branch to see if this has already been fixed
  • [X] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable

Description of the problem: In this example

static mut COUNTER: u32 = 0;

fn add_to_count(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

fn main() {
    add_to_count(3);

    unsafe {
        println!("COUNTER: {}", COUNTER);
    }
}

add_to_count is unsound because it is a safe fn that, when called from multiple threads, results in data races which are UB.

Suggested fix: Either mention that it is unsound and this code should not be copied in prose, or change the example like so:

static mut COUNTER: u32 = 0;

/// SAFETY: Must not be used to trigger data races
unsafe fn add_to_count(inc: u32) {
    COUNTER += inc;
}

fn main() {

    unsafe {
        add_to_count(3);
        println!("COUNTER: {}", COUNTER);
    }
}

nico-abram avatar Jan 21 '22 02:01 nico-abram

Regarding the fix, I think it should feature // Safety comments as well in the unsafe { … } block, about main not being called from other threads (since not called at all). It also encourages following the style of https://rust-lang.github.io/rust-clippy/master/#undocumented_unsafe_blocks

danielhenrymantilla avatar Jan 21 '22 11:01 danielhenrymantilla