Skip to content

"shares memory with another argument" error from reinterpreted view #29545

@tkf

Description

@tkf

Executing

buffer = zeros(UInt8, 4 * sizeof(Int))
mid = length(buffer) ÷ 2
x1 = reinterpret(Int, @view buffer[1:mid])
x2 = reinterpret(Int, @view buffer[mid+1:end])
x1 .= x2

throws:

ERROR: ArgumentError: an array of type Base.ReinterpretArray shares memory with another argument and must make a preventative copy of itself in order to maintain consistent semantics, but copy(A) returns a new array of type Array{Int64,1}. To fix, implement: Base.unaliascopy(A::Base.ReinterpretArray)::typeof(A)

I found that I can workaround it by unsafe_wrap:

buffer = zeros(UInt8, 4 * sizeof(Int))
mid = length(buffer) ÷ 2
y1 = reinterpret(Int, unsafe_wrap(Array, pointer(buffer, 1), mid))
y2 = reinterpret(Int, unsafe_wrap(Array, pointer(buffer, mid + 1),
                                  length(buffer) - mid))
y1 .= y2

But is there a less unsafe way to do it?

Note that a similar code using only view works:

z0 = collect(1:4)
z1 = @view z0[1:2]
z2 = @view z0[3:end]
z2 .= z1

so I suppose aliasing analysis can be done for reinterpreted view? If there is no safe way to do it, does it makes sense to add such feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions