Pointer dereferencing in Julia (unsafe_load(ptr) works but unsafe_wrap(Array, ptr, 1) segfaults)

Viewed 133

I'm trying to dereference pointer with unsafe_load and unsafe_wrap. I found out that unsafe_load works just nice, however unsafe_wrap crashes in case of dereferencing pointer to mutable struct. Toy example:

[mutable] struct Wrapper
    data::Int
end

some = Wrapper(1)
ptr = convert(Ptr{Wrapper}, Base.Libc.malloc(sizeof(Wrapper)))
unsafe_store!(ptr, some)

unsafe_load(ptr) # returns Wrapper(1)
unsafe_wrap(Array, ptr, 1) # segfaults if Wrapper is mutable, works fine if not

And I need exactly unsafe_wrap as it does not make a copy (I need to perform some operations in-place in allocated by malloc memory). Why does it segfault?

1 Answers

Found answer here

Vector of mutable structs is a vector of pointers i.e.

mutable struct Wrapper
    data::Int
end

a = Wrapper(1)
b = [a, a]
a.data = 2
b # is now Wrapper[Wrapper(2), Wrapper(2)]

So memory layout of Int and Wrapper are not the same.

Related