Skip to content

convert can lead to unexpected aliasing #12441

@IainNZ

Description

@IainNZ

Consider:

function foo(x)
  y = convert(Vector{Float64},x)
  y[1] = 10.0
  return y
end
julia> x = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> foo(x)
3-element Array{Float64,1}:
 10.0
  2.0
  3.0

julia> x
3-element Array{Int64,1}:
 1
 2
 3

julia> x = [1.,2.,3.]
3-element Array{Float64,1}:
 1.0
 2.0
 3.0

julia> foo(x)
3-element Array{Float64,1}:
 10.0
  2.0
  3.0

julia> x
3-element Array{Float64,1}:
 10.0
  2.0
  3.0

The input is modified in one case, and not the other, which is in the realms of "scary". One (The?) solution is to always do a copy, even if the type matches, for mutable types.

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