rust-lang / rust-lang/rust

`Vec::from_raw_parts` docs do not correctly handle empty buffers

Open
#119,304 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-collections A-docs T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Location

https://doc.rust-lang.org/std/vec/struct.Vec.html#method.from_raw_parts

Summary

The docs state the precondition "ptr must have been allocated using the global allocator, such as via the alloc::alloc function", which means that the following code is unsound since Vec::new does not allocate to produce the pointer:

fn reassemble<T>(mut v: Vec<T>) -> Vec<T> {
  let capacity = v.capacity();
  let ptr = v.as_mut_ptr();
  let length = v.len();
  std::mem::forget(v);
  unsafe {Vec::from_raw_parts(ptr, length, capacity)}
}

I believe this to be highly surprising, and probably unintended.

Vec::from_raw_parts should allow ptr not to be obtained from an allocation if capacity times the size of T is zero.

If the documentation is correct InPlaceDstBufDrop is unsound: https://github.com/rust-lang/rust/blob/master/library/alloc/src/vec/in_place_drop.rs#L37

String::from_raw_parts and Vec::from_raw_parts_in have the same issue.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Vec::from_raw_parts documentation at the linked location, then compare the related String::from_raw_parts and Vec::from_raw_parts_in docs. Read library/alloc/src/vec/in_place_drop.rs to understand the cited case. Done means the documentation consistently describes empty-buffer pointer requirements and the related APIs, with the wording reviewed for soundness.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.