Skip to content

Iterators over slices of ZST behave strange #42789

Closed
@RalfJung

Description

@RalfJung

The following test passes for slices over non-ZST, but fails for ZST:

fn slice_test<T>(x: &[T]) {
    let mut i = x.iter();
    i.next();
    let x1 = i.next().unwrap();
    let x2 = &x[1];
    let x3 = x.iter().nth(1).unwrap();
    assert_eq!(x1 as *const _, x2 as *const _);
    assert_eq!(x2 as *const _, x3 as *const _);
}

fn main() {
    slice_test(&[1,2,3]);
    slice_test(&[(),(),()]);
}

Playpen

While pointers to ZSTs don't really matter as they will never be dereferenced, I think providing consistent addresses for the same element would still make sense.
Yet, x2 turns out to be 0x55e742ee85dc, no idea where that address is coming from. The LLVM IR contains some undef, but I am not sure if that always indicates a problem.

Generally, the iterator's treatment of ZST's seems a little fishy. Below

impl<T> SliceIndex<[T]> for usize {
, the get methods defer to .offset to compute the address of an element of the slice. offset is only well-defined for in-bounds accesses, yet it is used here on a dangling pointer-to-ZST, with some non-0 offset.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions