From 069c397975b09edddce5af5e5e96fd86f7fe1cca Mon Sep 17 00:00:00 2001 From: Damian Gryski Date: Mon, 6 Mar 2023 13:14:33 -0800 Subject: [PATCH] reflect: fix off-by-one in Zero sizing Without this, pointers wouldn't be set to nil. Add some tests. --- src/reflect/value.go | 2 +- src/reflect/value_test.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/reflect/value.go b/src/reflect/value.go index 92f87086..3f879e29 100644 --- a/src/reflect/value.go +++ b/src/reflect/value.go @@ -1083,7 +1083,7 @@ func init() { } func Zero(typ Type) Value { - if typ.Size() < unsafe.Sizeof(uintptr(0)) { + if typ.Size() <= unsafe.Sizeof(uintptr(0)) { return Value{ typecode: typ.(*rawType), value: nil, diff --git a/src/reflect/value_test.go b/src/reflect/value_test.go index 7f26aa8a..08bd325a 100644 --- a/src/reflect/value_test.go +++ b/src/reflect/value_test.go @@ -266,6 +266,28 @@ func TestNamedTypes(t *testing.T) { } } +func TestZero(t *testing.T) { + s := "hello, world" + var sptr *string = &s + v := ValueOf(&sptr).Elem() + v.Set(Zero(v.Type())) + + sptr = v.Interface().(*string) + + if sptr != nil { + t.Errorf("failed to set a nil string pointer") + } + + sl := []int{1, 2, 3} + v = ValueOf(&sl).Elem() + v.Set(Zero(v.Type())) + sl = v.Interface().([]int) + + if sl != nil { + t.Errorf("failed to set a nil slice") + } +} + func addrDecode(body interface{}) { vbody := ValueOf(body) ptr := vbody.Elem()