Skip to content

Commit d52f648

Browse files
authored
fix possible memory confusion in unsafe slice cast
1 parent 6ff375d commit d52f648

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

utils.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"io"
77
"reflect"
8+
"runtime"
89
"strconv"
910
"strings"
1011
"time"
@@ -256,7 +257,12 @@ func strCmp(s1, s2 string) int {
256257
}
257258

258259
func unsafeFastStringToReadOnlyBytes(s string) []byte {
260+
b := make([]byte, 0)
259261
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
260-
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
261-
return *(*[]byte)(unsafe.Pointer(&bh))
262+
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
263+
bh.Data = sh.Data
264+
bh.Cap = sh.Len
265+
bh.Len = sh.Len
266+
runtime.KeepAlive(s)
267+
return b
262268
}

0 commit comments

Comments
 (0)