File: raw-pointer-ub.rs

package info (click to toggle)
rustc 1.87.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 925,564 kB
  • sloc: xml: 158,127; python: 36,039; javascript: 19,761; sh: 19,737; cpp: 18,981; ansic: 13,133; asm: 4,376; makefile: 710; perl: 29; lisp: 28; ruby: 19; sql: 11
file content (45 lines) | stat: -rw-r--r-- 1,598 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const MISALIGNED_LOAD: () = unsafe {
    let mem = [0u32; 8];
    let ptr = mem.as_ptr().byte_add(1);
    let _val = *ptr; //~ERROR: evaluation of constant value failed
    //~^NOTE: based on pointer with alignment 1, but alignment 4 is required
};

const MISALIGNED_STORE: () = unsafe {
    let mut mem = [0u32; 8];
    let ptr = mem.as_mut_ptr().byte_add(1);
    *ptr = 0; //~ERROR: evaluation of constant value failed
    //~^NOTE: based on pointer with alignment 1, but alignment 4 is required
};

const MISALIGNED_COPY: () = unsafe {
    let x = &[0_u8; 4];
    let y = x.as_ptr().cast::<u32>();
    let mut z = 123;
    y.copy_to_nonoverlapping(&mut z, 1);
    //~^ ERROR evaluation of constant value failed
    //~| NOTE inside `std::ptr::const_ptr
    //~| NOTE inside `copy_nonoverlapping::<u32>`
    //~| NOTE accessing memory with alignment 1, but alignment 4 is required
    // The actual error points into the implementation of `copy_to_nonoverlapping`.
};

const MISALIGNED_FIELD: () = unsafe {
    #[repr(align(16))]
    struct Aligned(f32);

    let mem = [0f32; 8];
    let ptr = mem.as_ptr().cast::<Aligned>();
    // Accessing an f32 field but we still require the alignment of the pointer type.
    let _val = (*ptr).0; //~ERROR: evaluation of constant value failed
    //~^NOTE: based on pointer with alignment 4, but alignment 16 is required
};

const OOB: () = unsafe {
    let mem = [0u32; 1];
    let ptr = mem.as_ptr().cast::<u64>();
    let _val = *ptr; //~ERROR: evaluation of constant value failed
    //~^NOTE: expected a pointer to 8 bytes of memory
};

fn main() {}