Skip to content

Fix dropping of uninitialised memory in tensor0 - #2632

Open
Ollie-Pearce wants to merge 1 commit into
sonos:mainfrom
Ollie-Pearce:fix-drop-of-uninit-memory
Open

Fix dropping of uninitialised memory in tensor0#2632
Ollie-Pearce wants to merge 1 commit into
sonos:mainfrom
Ollie-Pearce:fix-drop-of-uninit-memory

Conversation

@Ollie-Pearce

Copy link
Copy Markdown

tensor0 builds an uninitialised buffer and then writes to that value with an assignment operator. Assignment drops the uninitialised tensor before overwriting it with x.

let mut tensor = Tensor::uninitialized::<A>(&[]).unwrap();
tensor.as_slice_mut_unchecked::<A>()[0] = x;

Reproduction:

Test case:

#[test]
fn drop_of_uninit() {
    let _t: Tensor = tensor0(1.0f32);
}

Verifying with Miri:

cargo +nightly-2025-08-20 miri test -p tract-data --test repro

Miri output:

error: Undefined Behavior: constructing invalid value at .pointer: encountered 0, but expected something greater or equal to 1
    |
512 |         self.ptr.cast().as_non_null_ptr()
    |         ^^^^^^^^ Undefined Behavior occurred here
    |

Fix:

Replace the assignment operator with the std::ptr::write function which directly writes to x, fixing the drop of uninitialised memory.

@kali

kali commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

Hey, nice catch. My imaginary friend mention another possible occurences in data/src/tensor.rs:1440 and core/src/ops/array/range.rs:51 . Want to have a look at these too ?

@Ollie-Pearce

Copy link
Copy Markdown
Author

Thanks, I'll take a look sometime over the next couple of days :)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants