Printing data behind `&raw str`?

⚓ Rust    📅 2026-07-11    👤 surdeus    👁️ 1      

surdeus

These are just a few snippets written to play with the basics of unsafe.

2 unique refs

fn main() {
    let mut s = 5;
    
    let r1 = &raw mut s;
    let r2 = &raw mut s;
        
    unsafe { 
        println!("{:?} {:?}", r1, r2);
        println!("{:?} {:?}", *r1, *r2);
    }
}

Read random memory

fn main() {

    let r1 = 0x10 as *const i32;
    

    unsafe {
        println!("{:?}", *r1);
        // But how can I try to print the data they point to?
    }
}

Print raw string

Even though &str, &mut str can be printed, *mut str can not, and the data structure is printed (the fat pointer).

Why was it done to print the pointer, rather than the underlying data? Can the data be printed somehow (so that it crashes here)? Or why isn't it possible?

fn main() {
    let mut s = "hello".to_string();
    println!("Pointer: {:p}, Len: {}, Capacity: {}", 
    s.as_ptr(), s.len(), s.capacity());

    let r1 = &raw mut s[..];
    let r2 = &raw mut s[..];
    
   s.push_str(&" world".repeat(90));
    
    println!("Pointer: {:p}, Len: {}, Capacity: {}", 
    s.as_ptr(), s.len(), s.capacity());
    unsafe {
        println!("{:?} {:?}", r1, r2);
        // But how can I try to print the data they point to?
    }
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed