Initializing Array of Arrays with undef gives UndefRefError?

When you use Vector{T}(undef, n), the uninitialized elements of the vector will be filled with random data (whatever happens to be in memory) if T is an isbits type. If T is not an isbits type, then you will get an UndefRefError if you try to access an uninitialized element, since the element hasn’t been initialized with a pointer to an instance of the non-isbits type.

julia> isbitstype(Int)
true

julia> Vector{Int}(undef, 1)
1-element Array{Int64,1}:
 4588932080

julia> isbitstype(String)
false

julia> Vector{String}(undef, 1)
1-element Array{String,1}:
 #undef

julia> struct A
           x::Int
       end

julia> isbitstype(A)
true

julia> Vector{A}(undef, 1)
1-element Array{A,1}:
 A(4438511664)

julia> mutable struct B
           x::Int
       end

julia> isbitstype(B)
false

julia> Vector{B}(undef, 1)
1-element Array{B,1}:
 #undef
4 Likes