Skip to content

Commit e938de2

Browse files
minuxbroady
authored andcommitted
[release-branch.go1.4] runtime: don't return a slice with nil ptr but non-zero len from growslice
Fixes #10135. Change-Id: Ic4c5ab15bcb7b9c3fcc685a788d3b59c60c26e1e Signed-off-by: Shenghou Ma <[email protected]> Reviewed-on: https://go-review.googlesource.com/7400 Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-on: https://go-review.googlesource.com/14248 Reviewed-by: Andrew Gerrand <[email protected]>
1 parent a527bdb commit e938de2

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/runtime/slice.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ func growslice(t *slicetype, old sliceStruct, n int64) sliceStruct {
5353

5454
et := t.elem
5555
if et.size == 0 {
56-
return sliceStruct{old.array, old.len, cap}
56+
// append should not create a slice with nil pointer but non-zero len.
57+
// We assume that append doesn't need to preserve old.array in this case.
58+
return sliceStruct{unsafe.Pointer(&zerobase), old.len, cap}
5759
}
5860

5961
newcap := old.cap

test/fixedbugs/issue10135.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// run
2+
3+
// Copyright 2015 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
// Issue 10135: append a slice with zero-sized element used
8+
// to always return a slice with the same data pointer as the
9+
// old slice, even if it's nil, so this program used to panic
10+
// with nil pointer dereference because after append, s is a
11+
// slice with nil data pointer but non-zero len and cap.
12+
13+
package main
14+
15+
type empty struct{}
16+
17+
func main() {
18+
var s []empty
19+
20+
s = append(s, empty{})
21+
22+
for _, v := range s {
23+
_ = v
24+
}
25+
}

0 commit comments

Comments
 (0)