Skip to content

Commit d7423b5

Browse files
Merge pull request #136 from frankschae/gradient_cache_init
zero uninitialized memory in `GradientCache`
2 parents 9435f75 + 7699003 commit d7423b5

2 files changed

Lines changed: 9 additions & 9 deletions

File tree

src/gradients.jl

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ function GradientCache(
2525
_c2 = nothing
2626
end
2727
else
28-
_c1 = similar(x)
28+
_c1 = zero(x)
2929
_c2 = zero(real(eltype(x))) .* x
3030
end
3131
else
@@ -36,12 +36,12 @@ function GradientCache(
3636
_c2 = nothing
3737
end
3838
end
39-
_c3 = similar(x)
39+
_c3 = zero(x)
4040
else # the scalar->vector case
4141
# need cache arrays for fx1 and fx2, except in complex mode, which needs one complex array
4242
if fdtype != Val(:complex)
43-
_c1 = similar(df)
44-
_c2 = similar(df)
43+
_c1 = zero(df)
44+
_c2 = zero(df)
4545
else
4646
_c1 = zero(Complex{eltype(x)}) .* df
4747
_c2 = nothing
@@ -75,13 +75,13 @@ function finite_difference_gradient(
7575
if typeof(fx)==Nothing && typeof(c1)==Nothing && typeof(c2)==Nothing
7676
error("In the scalar->vector in-place map case, at least one of fx, c1 or c2 must be provided, otherwise we cannot infer the return size.")
7777
else
78-
if c1 != nothing df = similar(c1)
79-
elseif fx != nothing df = similar(fx)
80-
elseif c2 != nothing df = similar(c2)
78+
if c1 != nothing df = zero(c1)
79+
elseif fx != nothing df = zero(fx)
80+
elseif c2 != nothing df = zero(c2)
8181
end
8282
end
8383
else
84-
df = similar(f(x))
84+
df = zero(f(x))
8585
end
8686
end
8787
cache = GradientCache(df, x, fdtype, returntype, inplace)

src/jacobians.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ function JacobianCache(
9797
@assert eltype(fx1) == T2
9898
_fx = fx
9999
end
100-
_x2 = similar(_x1)
100+
_x2 = zero(_x1)
101101
JacobianCache{typeof(_x1),typeof(_fx),typeof(fx1),typeof(colorvec),typeof(sparsity),fdtype,returntype}(_x1,_x2,_fx,fx1,colorvec,sparsity)
102102
end
103103

0 commit comments

Comments
 (0)