Skip to content

SlotMap::with_capacity_and_key() integer overflow when capacity == usize::MAX #157

Open

Description

@yanfenghu

Hi,

I found a potential integer overflow issue in the with_capacity_and_key constructor through Kani formal verification.

Location: src/basic.rs:204

Current Code:

pub fn with_capacity_and_key(capacity: usize) -> Self {
let mut slots = Vec::with_capacity(capacity + 1); // Overflow when capacity == usize::MAX
slots.push(Slot { … });
// …
}
Problem:

When capacity = usize::MAX:

capacity + 1 wraps to 0 (integer overflow)

Vec::with_capacity(0) succeeds but allocates no space

Violates the “with_capacity” contract

First insertion will trigger reallocation

Impact:

Unexpected behavior when user passes extreme capacity values

Violates API contract

Suggested Fix:

pub fn with_capacity_and_key(capacity: usize) -> Self {
let actual_capacity = capacity.checked_add(1)
.expect(“capacity overflow: requested capacity too large”);
let mut slots = Vec::with_capacity(actual_capacity);
// …
}
Could you please confirm if this is a valid concern?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions