rust-lang/rust-memory-model

Reordering writes to before external function calls

Closed this issue · 1 comments

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.

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.