ARTICLE AD BOX
I have the following Go code:
package main import ( "fmt" "time" ) type ticker struct { ticker time.Ticker } func main() { var t1 ticker // var err error go func() { t1.start() // fmt.Printf("%p\n", &err) }() defer func() { t1.stop() }() time.Sleep(3 * time.Second) } func (t *ticker) start() { t.ticker = *time.NewTicker(1 * time.Second) go func() { for range t.ticker.C { fmt.Println("Ticker ticked.") } }() } func (t *ticker) stop() { t.ticker.Stop() }When I run this code, I get the following error:
$ go run main.go Ticker ticked. Ticker ticked. Ticker ticked. fatal error: unexpected signal during runtime execution [signal SIGBUS: bus error code=0x1 addr=0x1002ba730 pc=0x10024e940] goroutine 1 gp=0x140000021c0 m=0 mp=0x100387200 [running]: runtime.throw({0x1002c192a?, 0x1002704f0?}) ...However, if I uncomment the lines `
// var err errorand
// fmt.Printf("%p\n", &err)the error does not occur. I don't understand why this happens. Could someone explain this behavior?
I understand that copying the value of time.Ticker is not the correct way to use and I know how to fix the code. However, I am not trying to fix the code here. I want to understand why uncommenting the line prevents the error. And what happend unser the hood.
I suspect this behavior might be related to Go's escape analysis or memory management, but I am not entirely sure. Could someone explain why this happens?
$ go version go version go1.23.10 darwin/arm64