Skip to content

Commit ae41033

Browse files
fuweidishan16696
authored andcommitted
copy key before seeking in CreateBucketIfNotExists
It's follow-up of etcd-io#637. Signed-off-by: Wei Fu <[email protected]>
1 parent f011be0 commit ae41033

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

bucket.go

+9-8
Original file line numberDiff line numberDiff line change
@@ -201,22 +201,27 @@ func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
201201
return nil, errors.ErrBucketNameRequired
202202
}
203203

204+
// Insert into node.
205+
// Tip: Use a new variable `newKey` instead of reusing the existing `key` to prevent
206+
// it from being marked as leaking, and accordingly cannot be allocated on stack.
207+
newKey := cloneBytes(key)
208+
204209
if b.buckets != nil {
205-
if child := b.buckets[string(key)]; child != nil {
210+
if child := b.buckets[string(newKey)]; child != nil {
206211
return child, nil
207212
}
208213
}
209214

210215
// Move cursor to correct position.
211216
c := b.Cursor()
212-
k, v, flags := c.seek(key)
217+
k, v, flags := c.seek(newKey)
213218

214219
// Return an error if there is an existing non-bucket key.
215-
if bytes.Equal(key, k) {
220+
if bytes.Equal(newKey, k) {
216221
if (flags & common.BucketLeafFlag) != 0 {
217222
var child = b.openBucket(v)
218223
if b.buckets != nil {
219-
b.buckets[string(key)] = child
224+
b.buckets[string(newKey)] = child
220225
}
221226

222227
return child, nil
@@ -232,10 +237,6 @@ func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
232237
}
233238
var value = bucket.write()
234239

235-
// Insert into node.
236-
// Tip: Use a new variable `newKey` instead of reusing the existing `key` to prevent
237-
// it from being marked as leaking, and accordingly cannot be allocated on stack.
238-
newKey := cloneBytes(key)
239240
c.node().put(newKey, newKey, value, 0, common.BucketLeafFlag)
240241

241242
// Since subbuckets are not allowed on inline buckets, we need to

0 commit comments

Comments
 (0)