rust - Why is pointer arithmetic the cause of a segfault? -
why pointer arithmetic (without reading or writing data behind these pointers) cause of segfault?
#![allow(dead_code,unused_variables)] use std::cell::cell; struct bar<t: ?sized> { a: cell<usize>, value: t, } unsafe fn foo<t: ?sized>(v: &t) { let fake: &bar<t> = std::mem::zeroed(); // segfault on line // not reading or writing uninitialized data behind reference, // doing pointer arithmetic. not reading or writing // uninitialized vtable, copy vtable pointer. let fake_val = &fake.value; } fn main() { use std::any::any; let some_ref: &any = &42 &any; unsafe { foo(some_ref) }; }
output: segmentation fault
in rust, merely creating dangling reference undefined behavior! allows compiler perform aggressive optimizations around references, wouldn't possible otherwise.
in particular case, compiler generates code calculates offset field using align
value in vtable. tries dereference vptr causes segfault.
to have dangling pointer, shouldn't use reference, raw pointer. can have dangling raw pointers without problem!
let fake: *const bar<t> = std::ptr::null();
wiki
Comments
Post a Comment