Skip to content

Possible UB from use of uninitialized [&T; N] #126

Closed
@mbrubeck

Description

@mbrubeck

Creating an array with mem::uninitialized may be UB if the array's elements contain non-null types (like &T) or uninhabited types (like !) or other types that have invalid values.

This can result in undefined behavior even if you never read the elements directly while they are uninitialized. For example, this program prints "true" if optimizations are enabled, when built with current rustc:

fn main() {
    let x: Option<[&u8; 1]> = unsafe { Some(std::mem::uninitialized()) };
    println!("{}", x.is_none());
}

SmallVec isn't eligible for null pointer optimization, so it isn't affected by this. However, it's possible that a future Rust compiler could add other optimizations that break if SmallVec uses mem::uninitialized to create arrays of such types.

The ideal solution is to switch from uninitialized to the new MaybeUninit union (rust-lang/rfcs#1892) when it becomes stable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions