Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum size of an array in 32 bits?

Tags:

rust

According to the Rust Reference:

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 maximum isize value. This ensures that isize 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.

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.

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).

Is an array in 32 bits also limited to 2GB in Rust? Or not?

like image 383
Matthieu M. Avatar asked Sep 01 '15 06:09

Matthieu M.


People also ask

What is the maximum size of array?

The maximum allowable array size is 65,536 bytes (64K). Reduce the array size to 65,536 bytes or less. The size is calculated as (number of elements) * (size of each element in bytes).

What is the size of array in 32-bit C compiler?

On a typical 32-bit machine, sizeof(int) returns 4 bytes, so we would get a total of 20 bytes of memory for our array.

How many elements are in an array with a maximum index of 32?

Java uses an integer as an index to the array and the maximum integer store by JVM is 2^32. so you can store 2,147,483,647 elements in the array.

Why sizeof array is 8?

The size of any pointer is always 8 on your platform, so it's platform dependent. The sizeof operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.


1 Answers

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.

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.

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.

like image 132
Veedrac Avatar answered Oct 14 '22 15:10

Veedrac