How to manually free allocated memory (Pointer.malloc)

Hi there,

I use a pointer to allocate some memory:

@arr = Pointer.malloc(@arr_index_max, 0_f64)

Is it possible to free the memory manually?
Or how can I tell the GC to free the memory?


You can un-reference (pointer going out of the scope, pointer assigned to some other value/reference etc) the pointer so that GC can re-claim the memory.

Another possibility here could be you invoke Pointer#realloc with lower size or 0.

# un-reference
@arr = Pointer(Floa64).null   

# OR

# re-allocate pointer size
@arr = @arr.realloc(0)
1 Like

I use this little script for testing both versions:

puts "Start"
ptr = Pointer.malloc(1147483648_u64, 0_f64)
puts "wait"
sleep 3
puts "\nFree the allocated memory."
# ptr = Pointer(Float64).null
ptr = ptr.realloc(0)
puts "is free"
sleep 10
puts "end"

According to the task manager, the memory is only released after the script has ended.