Reshape() permanently locks underlying array (bug?)

I want to iteratively build a matrix by first append!(v, col) column vectors to a larger vector v, and then finally resizing to a matrix v2 when I’m finished. Once I’m finished with the matrix v2, I then want to empty!(v) and do the whole thing again, taking advantage of the fact that I can avoid some memory allocations.

The problem is: even if the matrix v2 has been GC’ed, Julia won’t let me me empty the original vector v claiming “cannot resize array with shared data”.

While this makes sense if v2 is still in scope, the error occurs even if it has been forcibly GC’ed:

v = rand(10)
v2 = reshape(v, 2, 5)
v2 = nothing
GC.gc(true)
empty!(v)  # ERROR: cannot resize array with shared data

What’s weird and definitely seems concerning to me (a bug?) is that I can bypass this behaviour if I first wrap v in a view:

v = rand(10)
v2 = reshape(view(v, :), 2, 5)
empty!(v)  # No error even though v2 is in scope!
push!(v, 2)
@assert v[1] == v2[1, 1]  # Still share same underlying array

In fact, v2 in this second example is still able to access emptied memory originally from v (!!).

2 Likes

If someone stumbles across this, there exists a corresponding issue on github: reshape and push! inconsistent behavior · Issue #33143 · JuliaLang/julia · GitHub

2 Likes