Hi, I still feel some difficulty in understanding garbage collection. My understanding is that Julia has the mark-and-sweep garbage collector, which marks a set of GC-rooted objects and other objects traceable (or reachable) from them, and then sweeps unmarked objects. In addition, the garbage collector is accurate, meaning only pointers to valid Julia objects are GC-rooted and traced in the marking process. I think this property makes the GC root placement more complicated to understand, and I’m not sure which objects exactly are GC-rooted in Julia.
For example, I have no idea why, in the follwing code taken from the standard library, we need to GC.@preserve
the object referenced by x
:
# base/deepcopy.jl
function deepcopy_internal(x::String, stackdict::IdDict)
if haskey(stackdict, x)
return stackdict[x]
end
y = GC.@preserve x unsafe_string(pointer(x), sizeof(x))
stackdict[x] = y
return y
end
Isn’t the string object referenced by x
GC-rooted? More generally, aren’t objects referenced by local variables in the call stack always GC-rooted? I would like to know how the GC root placement pass works and which objects are GC-rooted. I can find some description on this topic in a devdocs section, but it is not very helpful to me because I do not share the background knowledge required to understand its details.
Thank you in advance.