1

I'm trying this:

let mut a = Box::new([42; 1000000]);
a[1] = 42;
assert!(a.len() > 0);

I'm getting (because it's too big for a stack):

signal: 11, SIGSEGV: invalid memory reference

Please, suggest a working alternative (I need an array, not a Vec!).

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 2
    I strongly suspect `[42; 1000000]` will still allocate on the stack then copy it over to heap. That's where this error is originating from. Here's mine when I tried running this code: "thread '' has overflowed its stack." – Tanveer Badar Apr 16 '23 at 05:43
  • @SolomonUcko it doesn't, because they suggest to use a vector, while I still would like to have an array (without the overhead provided by the `Vec` implementation on top of it). Maybe you know how `Vec` does it inside and I can simply do the same? – yegor256 Apr 16 '23 at 05:45
  • @yegor256 Creating the vec will allocate the exact capacity required, so `into_boxed_slice` won't reallocate. For `u8`, with an opt-level of at least 2, it simply calls `__rust_alloc` and `memset`, the same things boxing would ideally do: https://rust.godbolt.org/z/GWcxjrWs1 – Solomon Ucko Apr 16 '23 at 05:56
  • @SolomonUcko can you please post a working code that is using all this? – yegor256 Apr 16 '23 at 06:07
  • @yegor256 there is literally multiple working examples in the linked duplicate, you dismiss them because you think they have an overhead, but they really don't, please don't evaluate solutions based on what you believe to be true, especially if you are this inexperienced with a language. – cafce25 Apr 16 '23 at 08:52
  • @cafce25 I did some measurements and the overhead is visible. That's why I'm looking for a faster solution, trying to optimise what `Vec` is doing. Sorry for being naive :) – yegor256 Apr 16 '23 at 08:53
  • 1
    So you've tested the version put up on godbolt by Solomon Ucko and it performs worse than what exactly? I'm very curious to see that benchmark. – cafce25 Apr 16 '23 at 09:10
  • @cafce25 my case is more complex than the example above, obviously. I'm trying to create `struct` A that would include a sequence of other structs B and there _won't_ be any interactions with the heap when A is created. I'm using an array of B. Then, I need to have a large collection of A, on heap. As you can see, `Vec` of B is not an option for me, since it interacts with the heap (which is terribly slow). – yegor256 Apr 16 '23 at 10:03
  • 2
    Either you want something on the heap in which case a solution using `Vec` is most likely as good as any or you don't. But your question is explicitly asking for data **on the heap** so I don't see how the usage of it in `Vec` is any problem. – cafce25 Apr 16 '23 at 10:09

0 Answers0