Skip to content

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

Closed
@LehmanHe

Description

@LehmanHe
$ 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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions