Question about GC.@preserve

Consider the following two patterns:

v = Vector(...)
GC.@preserve v begin
   # unsafe stuff using pointer(v) 
end

and

v = Vector(...)
# unsafe stuff using pointer(v) 
GC.@preserve v

Are there situations where the second pattern might cause trouble?

Yes. The second pattern is incorrect.

For an example that doesn’t depend on reasoning about compilation: Imagine a future version of Julia with a moving GC. (Objects can be moved to make better use of memory) Then the address of an object at any given time is not stable, if you need to observe and use the address, you must therefore use GC preserve to ensure that the object has a stable address while you are using the pointer.

To be clear this future version of Julia doesn’t exist right now, but folks are working towards that.

But even today that version is not correct, due to optimizations.

4 Likes