Skip to content

Unclear unwind safety for std::alloc::Allocator::{grow,shrink} #104224

Open
@kpreid

Description

@kpreid

Location

https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html

Summary

The documentation for the grow(), grow_zeroed(), and shrink() methods contains an implication that it is not unsound (though also not recommended) for these methods to panic.

Clients wishing to abort computation in response to an allocation error are encouraged to call the handle_alloc_error function, rather than directly invoking panic! or similar.

But, it is important for the caller to handle outcomes correctly to avoid either leaking or accessing freed memory:

If this returns Ok, then ownership of the memory block referenced by ptr has been transferred to this allocator. The memory may or may not have been freed, and should be considered unusable.

If this method returns Err, then ownership of the memory block has not been transferred to this allocator, and the contents of the memory block are unaltered.

Thus, I think that the documentation should also mention the caller's responsibility in case of unwind, i.e. if the call panics. I see two coherent possibilities:

  1. A panic is a bug in the allocator; the caller must make no assumptions, and thus must not touch ptr further (potentially leaking an allocation).
  2. A panic is a way of signaling allocation failure; it should be treated similarly to Err, and ptr is still valid. Therefore, unwinding should leave the owner of ptr in a valid state, and deallocate ptr on drop.

In either case, I think the documentation should explicitly describe unwind considerations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-allocatorsArea: Custom and system allocatorsA-docsArea: Documentation for any part of the project, including the compiler, standard library, and tools

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions