32 位数组的最大大小? [英] Maximum size of an array in 32 bits?
问题描述
根据 Rust 参考:
isize
类型是一个有符号整数类型,其位数与平台的指针类型相同.对象和数组大小的理论上限是最大 isize
值.这确保了 isize
可用于计算指向对象或数组的指针之间的差异,并且可以寻址对象内的每个字节以及末尾的一个字节.
The
isize
type is a signed integer type with the same number of bits as the platform's pointer type. The theoretical upper bound on object and array size is the maximumisize
value. This ensures thatisize
can be used to calculate differences between pointers into an object or array and can address every byte within an object along with one byte past the end.
这显然将一个数组限制在 32 位系统上最多 2G 元素,但是不清楚一个数组是否也限制到最多 2GB 内存.
This obviously constrain an array to at most 2G elements on 32 bits system, however what is not clear is whether an array is also constrained to at most 2GB of memory.
在 C 或 C++ 中,您可以将指向第一个和最后一个元素的指针转换为 char*
并获得这两个指针的差异;有效地将数组限制为 2GB(以免溢出intptr_t
).
In C or C++, you would be able to cast the pointers to the first and one past last elements to char*
and obtain the difference of pointers from those two; effectively limiting the array to 2GB (lest it overflow intptr_t
).
在 Rust 中,32 位数组是否也限制为 2GB?还是不行?
Is an array in 32 bits also limited to 2GB in Rust? Or not?
推荐答案
Vec
的内部结构将值限制为 4GB,均在 with_capacity
和 grow_capacity
,使用
The internals of Vec
do cap the value to 4GB, both in with_capacity
and grow_capacity
, using
let size = capacity.checked_mul(mem::size_of::<T>())
.expect("capacity overflow");
如果指针溢出,这将导致恐慌.
which will panic if the pointer overflows.
因此,Vec
分配的切片在 Rust 中也以这种方式进行了限制.鉴于这是由于分配 API 中的潜在限制,如果任何典型类型可以规避这一点,我会感到惊讶.如果他们这样做了,由于指针溢出,切片上的 Index
将是不安全的.所以我希望不会.
As such, Vec
-allocated slices are also capped in this way in Rust. Given that this is because of an underlying restriction in the allocation API, I would be surprised if any typical type could circumvent this. And if they did, Index
on slices would be unsafe due to pointer overflow. So I hope not.
不过,由于其他原因,可能仍然无法分配所有 4GB.特别是,allocate
不会让你分配超过 2GB(isize::MAX
字节),所以 Vec
仅限于此.
It might still not be possible to allocate all 4GB for other reasons, though. In particular, allocate
won't let you allocate more than 2GB (isize::MAX
bytes), so Vec
is restricted to that.
这篇关于32 位数组的最大大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!