Skip to content

Golang fmt.Println can change the value of the array? #36331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
LehmanHe opened this issue Dec 31, 2019 · 1 comment
Closed

Golang fmt.Println can change the value of the array? #36331

LehmanHe opened this issue Dec 31, 2019 · 1 comment

Comments

@LehmanHe
Copy link

LehmanHe commented Dec 31, 2019

$ go version
go version go1.13.5 darwin/amd64
go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/helinming/Library/Caches/go-build"
GOENV="/Users/helinming/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/helinming/go/go1.13.5/bin"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/Users/helinming/go/go1.13.5"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/Users/helinming/go/go1.13.5/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/3_/n49czj355hddd0__5yzx3n200000gn/T/go-build181924234=/tmp/go-build -gno-record-gcc-switches -fno-common"
var x struct {
    a bool
    b int16
    c []int32
}

func main() {
    //a := []int32{1 << 9}
    //x.c = a
    pb := (*[]int8)(unsafe.Pointer(uintptr(unsafe.Pointer(&x)) + unsafe.Offsetof(x.c)))
    *pb = []int8{5}
    println(x.c[0])  // 5
    println(x.c[0])  // 5
    fmt.Println(x.c[0])  // 5
    fmt.Println(x.c[0])  // 327685 why????????
}

fmt.Println the same x.c[0] twice, but got different result. why?

@ianlancetaylor
Copy link
Contributor

You are printing a []int8 as though it were a []int32. The results will depend on the contents of memory locations that you are not setting. Your code sets a single byte to 5, and then prints the contents of four bytes starting at that single byte. If the other other three bytes don't happen to contain 0, you will see values other than 5. It's certainly possible for the fmt package to change those bytes, since you didn't allocate them.

This is not a bug, so closing. If you want to ask questions about Go, please use a forum, not the issue tracker. See https://golang.org/wiki/Questions. Thanks.

@golang golang locked and limited conversation to collaborators Dec 30, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants