Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you deallocate memory with Go garbage collection disabled?

http://golang.org/ref/spec#Allocation

There is a way to allocate memory, but I don't see a way to deallocate memory (without the Go GC turned on).

If I wanted to write an OS using Go, I would need to either write a low level GC for Go or disable the Go GC. In the latter case, how could I free memory?

PS - this topic has been talked about extensively on the Go mailing list, but I wanted to pose this specific question to SO.

like image 280
Brenden Avatar asked Mar 22 '23 18:03

Brenden


1 Answers

You can free arbitrary memory by making runtime·free accessible to your program using cgo.

Build your own package called, for example, mem and create two files:

mem.go

package mem

import "unsafe"
import "reflect"

func FreePtr(p unsafe.Pointer)

func Free(v interface {}) {
    FreePtr(unsafe.Pointer(reflect.ValueOf(v).Elem().Pointer()))
}

runtime.c

// +build gc
#include <runtime.h>

void ·Free(void* foo) {
    runtime·free(foo);
}

Example usage (free a slice and print number of frees):

import "free/mem"

func main() {
    var m1, m2 runtime.MemStats

    runtime.ReadMemStats(&m1)
    c := make([]int, 10000)
    inspect.Free(&c)
    runtime.ReadMemStats(&m2)

    fmt.Printf("%d vs %d\n", m1.Frees, m2.Frees)
}

You should see that there was one more free than before.

like image 176
nemo Avatar answered Apr 24 '23 18:04

nemo