Memory is not released

Why, after exiting the function, memory is not freed up?
P.S. The consumption of memory is looking into the monitoring system.

package main

import (
	"fmt"
	"bufio"
	"os"
	"io/ioutil"
	"runtime"
	"runtime/debug"
)

func input(promt string)  {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print(promt)
	reader.ReadString('\n')
}

func loadData()  {
	b, _ := ioutil.ReadFile("/Users/user/Golang/temp/src/file")
	fmt.Println(b[:10])
	input("Big file read")
	b = nil


}

func main()  {
	for 1 == 1 {
		debug.FreeOSMemory() // trying to clear the memory
		runtime.GC() // trying to clear the memory
		input("Call loadData")
		loadData()
	}
}

The Go runtime can only attempt to return the memory. Ultimately, the OS decides when to take the freed memory away from the process.

BTW, I hope this code is only for learning or research. If you think you need FreeOSMemory in production you certainly have a deeper problem behind that to solve.

Thanks for the answer. This code is written only for testing the process of freeing memory.

Note that if you want to free memory up for some reason, you’ll want to have the Go runtime GC and free memory to the OS, then have the OS free up the memory. Doing it the other way around isn’t going to work as well.

By the way, you can do just for {}, you don’t need 1 == 1.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.