diff --git a/base/array.jl b/base/array.jl index f247c8a32dbee..10b2f35042787 100644 --- a/base/array.jl +++ b/base/array.jl @@ -687,9 +687,10 @@ function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T return collect_to!(new, itr, i+1, st) end end - i-1 < length(dest) && + lastidx = lastindex(dest) + i-1 < lastidx && throw(ErrorException("iterator returned fewer elements than its declared length")) - i-1 > length(dest) && + i-1 > lastidx && throw(ErrorException("iterator returned more elements than its declared length")) return dest end diff --git a/test/arrayops.jl b/test/arrayops.jl index c2d3469ac2118..dfcb774beb85f 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -2546,7 +2546,8 @@ end @test_throws ErrorException collect(InvalidIter2()) @test_throws ErrorException collect(Any, InvalidIter2()) @test_throws ErrorException collect(Int, InvalidIter2()) - @test_throws ErrorException [x for x in InvalidIter2()] - # Should also throw ErrorException - @test_broken length(Int[x for x in InvalidIter2()]) != 2 + # These cases cannot be tested without writing to invalid memory + # unless the function checked bounds on each iteration (#29458) + # @test_throws ErrorException [x for x in InvalidIter2()] + # @test_throws ErrorException Int[x for x in InvalidIter2()] end \ No newline at end of file