Habebit
Habebit

Reputation: 975

If I want to code in Rust securely, should I code without using pointer arithmetic?

I've read that pointer arithmetic in Rust can be done through the pointer.offset() function, but it always has to be implemented in unsafe code:

fn main() {
    let buf: [u32; 5] = [1, 2, 3, 4, 5];
    let mut ptr1: *const u32 = buf.as_ptr();
    unsafe {
        let ptr2: *const u32 = buf.as_ptr().offset(buf.len() as isize);
        while ptr1 < ptr2 {
            println!("Address {:?} | Value {}", ptr1, *ptr1);
            ptr1 = ptr1.offset(1);
        }
    }
}

If I want to code in Rust securely, should I code without using pointer arithmetic and just using the corresponding index of an array for example? Or is there any other way?

Upvotes: 0

Views: 893

Answers (2)

hellow
hellow

Reputation: 13430

If I want to code in Rust securely

Then you should not use unsafe. There are a few legit reasons for unsafe (e.g. accessing memory locations that are known and safe to use, e.g. on microcontrollers several registers), but generally you should not use it.

should I code without using pointer arithmetic and just using the corresponding index of an array for example

Yes. There is no reason (in this specific case) to use unsafe at all. Just use

for i in 0..buf.len() {
    println!("Value {}", buf[i]);
}

This code however is not considered as "rusty", instead use a for-loop

for i in &buf {
    println!("Value {}", i);
}

Upvotes: 9

Peter Hall
Peter Hall

Reputation: 58735

Using raw pointers like that is very unlikely[1] to be faster than an idiomatic for loop over an iterator:

fn main() {
    let buf: [u32; 5] = [1, 2, 3, 4, 5];
    for val in buf.iter() {
        println!("Address {:?} | Value {}", val as *const u32, val);
    }
}

This is also much easier to read and doesn't introduce memory unsafety risks.


1 In fact, your code compares two pointer values each iteration, so is likely to be much slower than the idiomatic for loop, which can often omit all bounds checks.

Upvotes: 7

Related Questions