Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

19.1 has an unsound example and does not explain it #3013

Closed
2 tasks done
nico-abram opened this issue Jan 21, 2022 · 1 comment · Fixed by #4062
Closed
2 tasks done

19.1 has an unsound example and does not explain it #3013

nico-abram opened this issue Jan 21, 2022 · 1 comment · Fixed by #4062

Comments

@nico-abram
Copy link

  • I have checked the latest main branch to see if this has already been fixed
  • 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 added a commit to nico-abram/book that referenced this issue Jan 21, 2022
@danielhenrymantilla
Copy link

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

@carols10cents carols10cents added this to the ch19 milestone Jan 22, 2022
@chriskrycho chriskrycho linked a pull request Oct 4, 2024 that will close this issue
@chriskrycho chriskrycho linked a pull request Oct 9, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
4 participants