Skip to content

Commit a04c0ec

Browse files
authored
fix possible memory confusion in unsafe slice cast
1 parent 277c1bf commit a04c0ec

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

bytes_unsafe.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"reflect"
77
"strconv"
88
"unsafe"
9+
"runtime"
910
)
1011

1112
//
@@ -32,11 +33,12 @@ func bytesToString(b *[]byte) string {
3233
}
3334

3435
func StringToBytes(s string) []byte {
36+
b := make([]byte, 0, 0)
37+
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
3538
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
36-
bh := reflect.SliceHeader{
37-
Data: sh.Data,
38-
Len: sh.Len,
39-
Cap: sh.Len,
40-
}
41-
return *(*[]byte)(unsafe.Pointer(&bh))
39+
bh.Data = sh.Data
40+
bh.Cap = sh.Len
41+
bh.Len = sh.Len
42+
runtime.KeepAlive(s)
43+
return b
4244
}

0 commit comments

Comments
 (0)