LibC - free mallocd memory

hello all, my Clang is not very advanced, Im trying to get the CPU Load average using LibC bindings,

  lib LibC
    fun getloadavg(avg : Pointer(Float64), nelem : Int32) : Int32
    fun free(ptr : Void*) : Void
  end

  def get_load_avg 
    avg = Pointer(Float64).malloc(3)
    if LibC.getloadavg(avg, 3) != -1
      load_avg = [avg[0], avg[1], avg[2]]
      ## Free mallocd pointer here
      LibC.free(avg)
    end

getting core dumps because free() errors out on “invalid pointer”

How can i free up my libc mallocs?

Thanks.

according to this post, setting pointer to null allows Crystal GC to clean out the memory?

Is this correct?

    avg = Pointer(Float64).malloc(3)
   
    # Call the C function to get load averages
    if LibC.getloadavg(avg, 3) != -1
      load_avg = [avg[0], avg[1], avg[2]]
      
      # free the mallocd memory
      avg = Pointer(Float64).null

You’re mixing up two different allocator mechanisms:

Pointer.malloc allocates memory via the garbage collector. You don’t have to manage it manually and in fact, must not free it explicitly.

LibC.free is intended to free memory allocated with LibC.malloc. You must not pass memory allocated with a different allocator.

2 Likes

got it, thanks