Skip to content

Conversation

@Fur0rem
Copy link

@Fur0rem Fur0rem commented Sep 11, 2025

When reading back an array from Futhark to Rust using values, if the output buffer has more capacity than the array's length, it will crash.

Here's a concrete example where I allocate a buffer of 5 elements for an array of 2.
Futhark code:

entry make_array_of_len (n: i64) : []i64 =
  iota n

Rust code:

use futhark_lib::{Config, Context, backends};
type Backend = backends::C;

fn main() {
    let config = Config::<Backend>::new();
    let context = Context::new(config);
    
    let mut buffer = Vec::with_capacity(5);
    let array = context.entry_make_array_of_len(2).unwrap();
    array.values(&mut buffer);
    
    dbg!(&buffer);
}

And when executed:

thread 'main' panicked at /.../futhark_lib.rs:316:21:
attempt to subtract with overflow

The issue was the code generated at line 79 of "template/array.rs":

out.reserve(len - out.capacity());

Specifically len - out.capacity() would underflow if out's capacity was already greater than len.

So I added a check to make sure it reserves more memory only when it is needed.
I tried the patch on the code earlier and it did fix the issue:

     Running `target/debug/fut_cargo`
[src/main.rs:11:5] &buffer = [
    0,
    1,
]

@luleyleo
Copy link
Owner

I've fixed the CI now. Can you rebase?

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