什么是内存泄漏
内存泄漏说白了就是分配的内存(或者变量)不再使用,但是并没有被gc回收,而是继续占用内存
内存泄漏场景
substring
var s0 string // 包级别变量
// A demo purpose function.
func f(s1 string) {
s0 = s1[:50]
//s0 和 s1 共用相同的底层memory block
// 尽管 s1 不再使用,但是 s0仍然存活状态
// 所以s1 的内存不会被回收,尽管只有 50 byte内存
// 被使用,但是其他内存都泄漏了。
}
func demo() {
s := createStringWithLengthOnHeap(1 << 20) // 1M bytes
f(s)
}
//可以用如下方式来避免
func f(s1 string) {
s0 = string([]byte(s1[:50]))
}
卡住的或没结束的goroutine
没用且没stop的定时器
time.Ticker 应该被stop,当不再使用时候
io读写流未close
func main() {
num := 6
for index := 0; index < num; index++ {
resp, _ := http.Get("https://www.baidu.com")
_, _ = ioutil.ReadAll(resp.Body)
}
fmt.Printf("此时goroutine个数= %d\n", runtime.NumGoroutine())
}