What is the maximum length of a vector?

Hi,
let v = vec![0_i32; 500_000_000]; // it's Ok
let v = vec![0_i32; 600_000_000]; // error: panicked at 'capacity overflow', src\liballoc\raw_vec.rs:777:5

600_000_000 < u32::MAX < u64::MAX
What type has capacity?

I assume you're on a 32bit platform
size_of::<u32>() * 600_000_000 > isize::max

Most major OSes can only allow half the address space for users processes, the kernel is mapped into the other half, so more than that probably wouldn't work.

In Rust no allocations can have size larger than isize::MAX. It's mostly because the LLVM's getelementptr instruction, which is used for safe ptr offset, takes isize.

2 Likes

isize::MAX >= i32::MAX = 2_147_483_647 > 600_000_000

I also have a 64 bit OS

How much RAM do you have, and how much is otherwise used? You are trying to allocate 2.4 GB, after all.

1 Like

It's isize::MAX < 600_000_000 * size_of<i32>()

4 Likes

I have 32Gb RAM on 64-bit OS

it's true,
but panicked at 'capacity overflow', and capacity stores the number of elements, not the size of the memory they occupy

True, but the error message is generated here

When you try to allocate memory, which only cares about the number of bytes to allocate, not how many elements.

1 Like

you practically convinced me)
but I still don’t understand what exactly is being overflowed in this case:
the capacity of the vector is not, since this is still the number of elements (and not the number of bytes),
RAM - I have 32 GB of it, and it requires only 2.4 GB
don't be mad at my stubbornness, I just want to understand.

P.S.although you’re probably right, because:
let v = vec![0_u16; 600_000_000]; - Ok

thanks, the question is cleared

If you build your Rust code for a 64-bit target, you’ll be able to use all your RAM. 32-bit programs can only use 2GB.

2 Likes