Pointer Iteration Issue

Consider this example :

unsafe {
    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 :

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

What did I mistake, or is it a bug?

Thanks

1 Like

The *ptr = ... lines are exceeding the buffer memory. The lines with ptr = ptr.add(...); must be ptr = ptr.add(1);, since you are updating the ptr variable.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.