Does this still crash on new Julia versions?

#GC.enable(false) 
a = [1,2,3,4,5]
b = [Ptr{Int64}(i) for i in a]
#a = nothing
c = Base.unsafe_convert(Ptr{Ref{Int}},b)
d = unsafe_wrap(Array,c,5)
#Even with GC disabled, the crash still exists.

It asked me to file a bug report. However, my Julia version is not the most recent so it might be fixed in modern versions.

It’s not a bug — you can easily crash Julia by doing invalid operations with unsafe pointers. e.g. unsafe_load(Ptr{Int}(0)) also crashes.

In your example, you are taking e.g. the first element 1 of a, and calling Ptr{Int64}(1) for the first element of b, whcih is already a pointer to an invalid memory address 1. Then you are trying to reinterpret b as an array of pointers to Ref{Int} (an abstract type), which is also wrong.

Pointer operations are crucial to inter-operate with C libraries, for example. But they are marked “unsafe” for a reason — you have to know what you are doing, and use them in sensible ways.

5 Likes

Oh, thank you. I thought Ptr{Int}(1) would be a pointer to 1. I was playing with some cursed code.

To get a valid pointer to an element of a you can use the pointer function:

p = pointer(a, 1)
unsafe_load(p)

Note that pointer doesn’t do bounds checks, so you can ask for an element past the end of the intended array:

julia> unsafe_load(pointer([1, 2, 3], 4))
136772842288784