How to check whether a variable is unreachable?

201 views
Skip to first unread message

Cholerae Hu

unread,
Sep 22, 2021, 4:22:00 AM9/22/21
to golang-nuts
https://play.golang.org/p/WJTH-lUukeb

Do I need to uncomment line 23? IMHO, variable data and ds will not be used after line 16, so they can be collected in runtime.GC. But running it with gccheckmark=1 and clobberfree=1 doesn't show any problems.

Are there any documents about the details or behavior of liveness analysis? 

Ian Lance Taylor

unread,
Sep 22, 2021, 6:11:48 PM9/22/21
to Cholerae Hu, golang-nuts
I don't see any reason why that program should need runtime.KeepAlive.

The local variable sh will point to data (aka ds), so the object will
stay alive. This is not different than p := &data. After that point,
if data is no longer mentioned, then the variable data is no longer
live, but the value that p points to will remain alive.

Ian

Cholerae Hu

unread,
Sep 23, 2021, 2:23:47 AM9/23/21
to golang-nuts
Thanks, I see. How about this one? I use a temp variable to store sh.Data, sh/ds/data are all no longer mentioned at the point when unsafe.Slice is called. Do I need to use runtime.KeepAlive? 

package main

import (
"fmt"
"reflect"
"runtime"
"unsafe"
)

var b []byte

func f(data interface{}) {
switch ds := data.(type) {
case []int32:
sh := (*reflect.SliceHeader)(unsafe.Pointer(&ds))
l := len(ds)
d := sh.Data
runtime.GC()
b = unsafe.Slice((*byte)(unsafe.Pointer(d)), l*4)
}
// runtime.KeepAlive(data)
}

func main() {
f([]int32{1, 2})
runtime.GC()
fmt.Println(b)
}

jake...@gmail.com

unread,
Sep 23, 2021, 8:11:46 AM9/23/21
to golang-nuts
I'm pretty sure new example is not valid Go code to begin with. You violate the rules on converting from uintptr to unsafe.Pointer. If you read the rules at https://pkg.go.dev/unsafe#Pointer, a unitptr can not generally be converted to an unsafe.Pointer. Since this code is not valid, the question is pretty much moot.

peterGo

unread,
Sep 23, 2021, 8:28:28 AM9/23/21
to golang-nuts
$ go vet ch.go
# command-line-arguments
./ch.go:19:28: possible misuse of unsafe.Pointer
$


Peter

On Thursday, September 23, 2021 at 2:23:47 AM UTC-4 chole...@gmail.com wrote:

peterGo

unread,
Sep 23, 2021, 8:36:11 AM9/23/21
to golang-nuts

Package runtime

Documentation

func KeepAlive

Note: KeepAlive should only be used to prevent finalizers from running prematurely.

Peter

On Thursday, September 23, 2021 at 2:23:47 AM UTC-4 chole...@gmail.com wrote:

Cholerae Hu

unread,
Sep 23, 2021, 11:26:39 PM9/23/21
to golang-nuts
I get it. Thanks for all your responses!
Reply all
Reply to author
Forward
0 new messages