I want to simulate a allocation system trough the two following functions
alloc_float(n) = unsafe_wrap(Array, convert(Ptr{Float64},Libc.calloc(n, 8)), n)
macro free(p)
:(Libc.free(pointer($p)); p = nothing) # does not work with $p = nothing
end
If I used the 2 functions
julia> w = alloc_float(3)
3-element Vector{Float64}:
0.0
0.0
0.0
julia> @free w
julia> w
3-element Vector{Float64}:
2.86883399e-315
2.90896374e-315
1.6e-322
the w still remains in the Main space variable even if it points on bad memory area.
The question here is about the macro and why it does not work, not about the pertinence of that two functions.
It has to do with how Julia handles macro hygiene, expression evaluation order, and variable reassignment in outer scopes. $p correctly interpolates the variable name w into pointer(w). However, p = nothing inside the quote block creates a local binding inside the expanded code block that doesn’t bind back to the caller’s variable w.
So, escaping is needed for memory de-allocation and re-binding in the calling context.
macro free(p)
quote
Libc.free(pointer($(esc(p))))
$(esc(p)) = nothing
end
end