rust-lang / rust-memory-model

Collecting examples and information to help design a memory model for Rust.
Apache License 2.0
126 stars 15 forks source link

Reordering writes to before external function calls #25

Closed arielb1 closed 8 years ago

arielb1 commented 8 years ago

Code example:

extern "C" {
    fn abort_if(condition: bool);
}

fn example(index: usize) {
    unsafe {
        let mut buf: [u8; 1024] = [0; 1024];
        abort_if(index >= 1024);
        *buf.get_unchecked_mut(index) = 0xff;
    }
}

This must call abort_if before the unchecked_get_mut - i.e. if abort_if has the obvious implementation, this code must never be UB.

This seems obvious to me, but according to some people, doing the write first is Perfectly Legal because of UB.

strega-nil commented 8 years ago

However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

The important thing is "if any such execution contains an undefined operation". No execution of the code given contains an undefined operation.