Julia is Overwriting output of a Function

Hello,

I am having a very weird behavior in Julia, however, I am having a hard time reproducing it in a MWE. Let me try to describe it, with an example which does not reproduce the error

function test(x,y)

        results = 0.0

        results = x+y

        return results

    end 

    Result_1 = test(1,2)

    Result_2 = test(1,7)

After doing this, Result_1 == Result_2 is true. As I was saying this function does not reproduce the error, however, it captures the idea of what is happening in the actual problematic function. I run it with two different inputs, and the second run overwrites the value of the first run.

This is the function where this is happening. Could this possibly be related with the SharedArrays ?


	function counterfactuals_generator(ZSeeds_cf,FSeeds_cf,ProbsSeeds,seeds_climate_cf,β,α,τ,J,Ι,S,Simul,N,params)
		(κ,σ,σ₁,σ₂,χ)=params
		κt = (κ)^(1/σ)
		μ = params[6:end]
		println(1000000 .*μ)
		ftemp = σ₁.*FSeeds_cf .+ 1000000 .*μ.*ones(size(FSeeds_cf))
		F = exp.(ftemp)
		#F = zeros(size(F))

		κᵢ = κt.*(seeds_climate_cf .< ProbsSeeds)
		κᵢ[κᵢ .== 0.0] .= 1.0

		ztemp = σ₂*ZSeeds_cf .+ 0.0.*ones(size(ZSeeds_cf))
		Z = exp.(ztemp)

		taus = exp.(τ).^(-1/σ)
		

		Random.seed!(0607)
		ParetoDraws = rand(Pareto(χ,0.783),N)

		ϕ(φ) = φ^(σ-1)*(σ/(σ-1))^(1-σ)*1/σ

		FirmShifters = ϕ.(ParetoDraws)
		println("Computing Marginal Costs")
		mc_simul=marginalcost_cf(κᵢ,Z,α,taus,Ι,J,S,N,Simul)
		solution=SharedArray{Int8}(Ι,N,Simul)
		policies=SharedArray{Int8}(Ι,J,S,N,Simul)
		profit=SharedArray{Float64}(N,Simul)
		
		println("Pre-Stuff Done")
		for s = 1 : Simul
			println(s)
			@sync @distributed for n=1:N
			#println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Firm # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: ", n)
			sol = firmproblem(mc_simul[:,:,:,n,s],σ,F[:,n,s],J,Ι,S,κ,FirmShifters[n],β)
			solution[:,n,s]= sol[1]
			policies[:,:,:,n,s]=sol[2]
			profit[n,s] = sol[3]
			#println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Firm # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: ", n)
			end
		end
		return solution, policies, FirmShifters, F, κᵢ, mc_simul, profit
	end		

Seems that returning a copy of solution, policies and profit solves the issue. Interesting, because it seems that this does not happen all the time.

You have probably been bitten by

julia> a = [1]
1-element Vector{Int64}:
 1

julia> b = a
1-element Vector{Int64}:
 1

julia> b[1] = 2
2

julia> a
1-element Vector{Int64}:
 2

the line b = a will just assign a new name b to the data that is referenced by a, and both b and a will point to the same memory. Returning a copy thus solves the problem since the memory is then copied and they no longer reference the same.