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?

Thanx

1 Like

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)
2 Likes

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.

You’ll find the same thing with a C program. For example:

#include <stdio.h>                                                               
#include <stdlib.h>                                                              
#include <unistd.h>                                                              
                                                                                 
int main(void)                                                                   
{                                                                                
    char *c = malloc(1147483648);                                                
    for (int i = 0; i < 1147483648; ++i) c[i] = 1;                               
    printf("wait\n");                                                            
    sleep(3);                                                                    
    free(c);                                                                     
    printf("is free\n");                                                         
    sleep(10);                                                                   
    return 0;                                                                    
}             

Often, calling free doesn’t actually release the memory back to the OS. But if you were to make another allocation in the same execution of the same program, the freed memory would get re-used. So free is just telling the memory allocation machinery that the memory can be used again another time malloc is called.

3 Likes