爲什麼這個指針算術(沒有在這些指針後面讀寫數據)導致段錯誤?爲什麼指針算術是段錯誤的原因?
#![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 this line
// we are not reading or writing uninitialized data behind the reference,
// but only doing pointer arithmetic. We are not reading or writing
// uninitialized vtable, but only copy the vtable pointer.
let fake_val = &fake.value;
}
fn main() {
use std::any::Any;
let some_ref: &Any = &42 as &Any;
unsafe { foo(some_ref) };
}
輸出:Segmentation fault
如果可以安全地使用一個帶有原始指針的懸掛指針,爲什麼它會顯示與OP代碼相同的行爲(例如,在調試中失敗,在Release中爲「有效」) https://play.rust-lang。 org /?gist = 23baa08f2c83609e002f33b3e2852543&version = stable – Timidger
@Timidger因爲您取消引用了第二行中的指針。解引用懸掛指針當然是不允許的。所以你不能用'.'運算符得到指向該字段的指針。說實話,我不知道獲得這樣一個指向字段的指針的最佳方式是什麼。最好問另一個問題! :) –