(); } 我得到: thread '' panicked at 'capacity-6ren">
gpt4 book ai didi

linux - 在 i::count 上运行收集时得到 "Illegal instruction"

转载 作者:太空狗 更新时间:2023-10-29 12:03:04 26 4
gpt4 key购买 nike

运行这个:

fn main() {
std::iter::count(1i16, 3).collect::<Vec<i16>>();
}

我得到:

thread '' panicked at 'capacity overflow', /home/tshepang/projects/rust/src/libcore/option.rs:329

这就是我在运行时所期望的:

fn main() {
std::iter::count(1i8, 3).collect::<Vec<i8>>();
}

但相反,我得到了这个:

Illegal instruction

此外,系统日志显示此行:

Dec 27 08:31:08 thome kernel: [170925.955841] traps: main[30631] trap invalid opcode ip:7f60ab175470 sp:7fffbb116578 error:0 in main[7f60ab15c000+5b000]

最佳答案

这是一次有趣的冒险。

Iter::collect只需调用 FromIterator::from_iter

Vec's implementation of FromIterator向迭代器询问其大小,然后分配内存:

let (lower, _) = iterator.size_hint();
let mut vector = Vec::with_capacity(lower);

Vec::with_capacity计算内存的总大小并尝试分配它:

let size = capacity.checked_mul(mem::size_of::<T>())
.expect("capacity overflow");
let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
if ptr.is_null() { ::alloc::oom() } // Important!

在这种情况下,i8 占用 1 个字节,无限迭代器 的下界是 std::uint::MAX。相乘后,仍然是 std::uint::MAX。当我们分配它时,我们得到一个空指针。

alloc::oom被定义为简单的中止,这是由非法指令实现的!

i16 具有不同行为的原因是因为它触发了 checked_mul 期望 - 你不能分配 std::uint::MAX * 2 字节!


在现代 Rust 中,示例将写成:

(1i16..).step_by(3).collect::<Vec<_>>();
(1i8..).step_by(3).collect::<Vec<_>>();

现在两者都以相同的方式失败:

memory allocation of 12297829382473034412 bytes failed
memory allocation of 6148914691236517206 bytes failed

关于linux - 在 i::count 上运行收集时得到 "Illegal instruction",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664956/

26 4 0
文章推荐: html - 使用 list-style-type :none 删除
文章推荐: html - 如何链接到另一个页面上的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com