This is an automated archive.

The original was posted on /r/golang by /u/Successful-Long-6532 on 2023-09-02 00:45:20+00:00.


Hey folks,

I’m diving into Golang and having a blast experimenting with the compiler tool to better understand how memory allocation works, like what gets tossed onto the heap and what hangs out on the stack.

So, I stumbled upon this VIDEO that breaks down how the Go compiler handles memory, and it was awesome… until it wasn’t! I tried to replicate a stack-based example shown in the video. I literally copied and pasted the code, but guess what? It didn’t work as expected. According to both the video and the documentation, certain code blocks should be chilling on the stack, but they decided to party on the heap instead:

Ex1 => n2 supposed to not escape to heap:

package main

import "fmt"

func main() {
 n := 4
 n2 := square(n)

fmt.Println(n2)


}

func square(y int) int {
 return y \* y
}

CMD + Result:

===============================RESULT=========================
go build -gcflags="-m" main\_stack.go 

command-line-arguments
======================

./main\_stack.go:12:6: can inline square 
./main\_stack.go:7:14: inlining call to square 
./main\_stack.go:9:13: inlining call to fmt.Println 
./main\_stack.go:9:13: ... argument does not escape 
./main\_stack.go:9:14: n2 escapes to heap

This is leaving me scratching my head. It’s like a little bug in the matrix. Has anyone else run into this? Any insights, experiences, or solutions would be absolutely awesome.

Thank you all!