Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust pointer iteration issue

I try to iterate pointer from an allocated array.

Consider this example :

let layout = Layout::array::<u32>(5).unwrap();

let mut ptr = alloc(layout) as *mut u32;

let base = ptr;

ptr = ptr.add(0);
*ptr = 10;
ptr = ptr.add(1);
*ptr = 100;
ptr = ptr.add(2);
*ptr = 200;
ptr = ptr.add(3);
*ptr = 300;
ptr = ptr.add(4);
*ptr = 400;


let a = *base.add(0);
let b = *base.add(1);
let c = *base.add(2);
let d = *base.add(3);
let e = *base.add(4);

result is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a : 10
b : 100
c : 0
d : 200
e : 0

What did I mistake, or is it a bug?

Thanks

>Solution :

You’re setting the following values:

  • base.add(0) via ptr.add(0)
  • base.add(1) via ptr.add(1)
  • base.add(3) via ptr.add(2) (on the already modified pointer)
  • and so on:
ptr = ptr.add(0); // total offset =  0
*ptr = 10;
ptr = ptr.add(1); // total offset =  1
*ptr = 100;
ptr = ptr.add(2); // total offset =  3 <--- whoops!
*ptr = 200;
ptr = ptr.add(3); // total offset =  6 <--- undefined behavior!
*ptr = 300;
ptr = ptr.add(4); // total offset = 10 <--- further undefined behavior
*ptr = 400;

You either need to keep the original pointer or only use ptr.add(1) to advance to the next location.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading