From a04c0ece70b47c803514cdba34618fe04cfc16a8 Mon Sep 17 00:00:00 2001 From: Johannes Lauinger Date: Sat, 30 May 2020 01:59:29 +0200 Subject: [PATCH] fix possible memory confusion in unsafe slice cast --- bytes_unsafe.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/bytes_unsafe.go b/bytes_unsafe.go index d3f523d..589fea8 100644 --- a/bytes_unsafe.go +++ b/bytes_unsafe.go @@ -6,6 +6,7 @@ import ( "reflect" "strconv" "unsafe" + "runtime" ) // @@ -32,11 +33,12 @@ func bytesToString(b *[]byte) string { } func StringToBytes(s string) []byte { + b := make([]byte, 0, 0) + bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) - bh := reflect.SliceHeader{ - Data: sh.Data, - Len: sh.Len, - Cap: sh.Len, - } - return *(*[]byte)(unsafe.Pointer(&bh)) + bh.Data = sh.Data + bh.Cap = sh.Len + bh.Len = sh.Len + runtime.KeepAlive(s) + return b }