Bug in julia zeros() side effects

Julia Version 1.7.2 (2022-02-06)

I experienced some side effects of the initialization with zeros.
Good to know…

buggy

function compute_k1!(nfft::Int64,kvec::Vector{ComplexF64})
kvec=zeros(ComplexF64,nfft)
for i=1:nfft
kvec[i]=i+1im
end
end

no bug

function compute_k2!(nfft::Int64,kvec::Vector{ComplexF64})
for i=1:nfft
kvec[i]=i+1im
end
end

nfft=10
kvec1=zeros(ComplexF64,nfft)
compute_k1!(nfft,kvec1)
println(kvec1)
kvec2=zeros(ComplexF64,nfft)
compute_k2!(nfft,kvec2)
println(kvec2)

first println
10-element Vector{ComplexF64}:
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
second println
ComplexF64[1.0 + 1.0im, 2.0 + 1.0im, 3.0 + 1.0im, 4.0 + 1.0im, 5.0 + 1.0im, 6.0 + 1.0im, 7.0 + 1.0im, 8.0 + 1.0im, 9.0 + 1.0im, 10.0 + 1.0im]

Obviously there is side effects on using zeros…

This isn’t a bug. This is just that Julia is pass by sharing.

2 Likes

In the function compute_k1! you create a local array which masks kvec
passed as argument. The argument is not modified. Delete the line which
calls zeros. If you really want to set kvec to zero on that line, use kvec .= zero(eltype(kvec)).

5 Likes

Thank you for the response, topics closed

When posting code, please make sure to wrap it in triple backticks so it gets formatted. You can read about it here:

1 Like