Skip to content

Incorrect unsafe code example in standard library #77220

Closed
@TrolledWoods

Description

@TrolledWoods

The safety clause on the Vec::set_len function says that:

  • new_len must be less than or equal to capacity().
  • The elements at old_len..new_len must be initialized.

However, the code example for std::ptr::copy violates the second rule

use std::ptr;

unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
    let mut dst = Vec::with_capacity(elts);
    dst.set_len(elts);
    ptr::copy(ptr, dst.as_mut_ptr(), elts);
    dst
}

The set_len is called before the values are initialized with the copy.

This could be fixed by either making the safety clause for set_len more inclusive, so that as long as you don't use the vector before initializing the values it's considered safe, or by switching the dst.set_len(elts); and ptr::copy(ptr, dst.as_mut_ptr(), alts); lines around in the example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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