Skip to content

Miri reports UB in safe code due to address space exhaustion (?) #2769

Closed
rust-lang/rust
#107756
@saethlin

Description

@saethlin

On a 32-bit target, Miri says this program encounters UB:

fn main() {
    for _ in 0..4 {
        let a = [0u8; 1024 * 1024 * 1024];
        drop(&a[..]);
    }
}
error: Undefined Behavior: overflowing in-bounds pointer arithmetic
 --> src/main.rs:4:15
  |
4 |         drop(&a[..]);
  |               ^ overflowing in-bounds pointer arithmetic
  |
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
  = note: BACKTRACE:
  = note: inside `main` at src/main.rs:4:15: 4:16

The program above is a bit slow to execute but it gets the job done without any unsafe. Using Vec::with_capacity is faster.

I feel like this shouldn't be possible? Or at least we shouldn't report UB?


The Vec version is this:

fn main() {
    for _ in 0..4 {
        let mut a: Vec<u8> = Vec::with_capacity(1024 * 1024 * 1024);
        drop(a.spare_capacity_mut().as_ptr());
    }
}
error: Undefined Behavior: overflowing in-bounds pointer arithmetic
 --> src/main.rs:4:14
  |
4 |         drop(a.spare_capacity_mut().as_ptr());
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ overflowing in-bounds pointer arithmetic
  |
  = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
  = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
  = note: BACKTRACE:
  = note: inside `main` at src/main.rs:4:14: 4:45

In this case I think it's much more clear that the last allocation should fail

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