yskyj
yskyj

Reputation: 141

slice bounds out of range when using unsafe.Pointer

I am faced up with a curious panic when I trim a byte array using syntax like b[1:2] which is converted from []byte to string and then back to []byte.

My go version is go1.7.3 darwin/amd64. What belows is the detail code.

package main

import (
            "reflect"
            "unsafe"
            "fmt"

)

func BytesToString(b []byte) string {
    bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    sh := reflect.StringHeader{bh.Data, bh.Len}
    return *(*string)(unsafe.Pointer(&sh))
}

func StringToBytes(s string) []byte {
    sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh := reflect.SliceHeader{sh.Data, sh.Len, 0}
    return *(*[]byte)(unsafe.Pointer(&bh))
}

func main() {
b := []byte{'b', 'y', 't', 'e'}

// No1  here you can trim []byte using b[1:2]
_ = b[1:2]
fmt.Println("No1")

// convert []byte to string
s := BytesToString(b)

// convert string to []byte
b = StringToBytes(s)

// create new []byte variant using content of b
bb := make([]byte, len(b))
for i := 0; i < len(b); i++ {
    bb[i] = b[i]
}

// No2 here you also can trim []byte using bb[1:2]
_ = bb[1:2]
fmt.Println("No2")

// No3 here you can not trim []byte. I don't know why. why?
_ = b[1:2]
fmt.Println("No3")

}

Run this code, and get error as follows:

 No1
 No2
 panic: runtime error: slice bounds out of range

 goroutine 1 [running]:
 panic(0x8f060, 0xc42000a100)
 /usr/local/Cellar/go/1.7.3/libexec/src/runtime/panic.go:500 +0x1a1
 main.main()
 /tmp/unsafe.go:45 +0x274
 exit status 2

I'm curious about what caused this panic?

Upvotes: 0

Views: 541

Answers (1)

Thundercat
Thundercat

Reputation: 121139

The capacity of the slice created by StringToBytes is zero.

The for loop does not panic because index expressions check len(b).

The expression b[1:2] panics because slice expressions check cap(b).

One fix is to set capacity to the length of the string:

func StringToBytes(s string) []byte {
    sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh := reflect.SliceHeader{sh.Data, sh.Len, sh.Len}
    return *(*[]byte)(unsafe.Pointer(&bh))
}

Upvotes: 3

Related Questions