Skip to content

Commit 59b8453

Browse files
authored
Merge pull request #550 from fyfyrchik/heap-alloc-key
bucket: allow to allocate key on stack in Put()
2 parents 0855b96 + 71a59ca commit 59b8453

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

bucket.go

+14-8
Original file line numberDiff line numberDiff line change
@@ -175,15 +175,17 @@ func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
175175
var value = bucket.write()
176176

177177
// Insert into node.
178-
key = cloneBytes(key)
179-
c.node().put(key, key, value, 0, common.BucketLeafFlag)
178+
// Tip: Use a new variable `newKey` instead of reusing the existing `key` to prevent
179+
// it from being marked as leaking, and accordingly cannot be allocated on stack.
180+
newKey := cloneBytes(key)
181+
c.node().put(newKey, newKey, value, 0, common.BucketLeafFlag)
180182

181183
// Since subbuckets are not allowed on inline buckets, we need to
182184
// dereference the inline page, if it exists. This will cause the bucket
183185
// to be treated as a regular, non-inline bucket for the rest of the tx.
184186
b.page = nil
185187

186-
return b.Bucket(key), nil
188+
return b.Bucket(newKey), nil
187189
}
188190

189191
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
@@ -230,15 +232,17 @@ func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
230232
var value = bucket.write()
231233

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

236240
// Since subbuckets are not allowed on inline buckets, we need to
237241
// dereference the inline page, if it exists. This will cause the bucket
238242
// to be treated as a regular, non-inline bucket for the rest of the tx.
239243
b.page = nil
240244

241-
return b.Bucket(key), nil
245+
return b.Bucket(newKey), nil
242246
}
243247

244248
// DeleteBucket deletes a bucket at the given key.
@@ -333,8 +337,10 @@ func (b *Bucket) Put(key []byte, value []byte) error {
333337
}
334338

335339
// Insert into node.
336-
key = cloneBytes(key)
337-
c.node().put(key, key, value, 0, 0)
340+
// Tip: Use a new variable `newKey` instead of reusing the existing `key` to prevent
341+
// it from being marked as leaking, and accordingly cannot be allocated on stack.
342+
newKey := cloneBytes(key)
343+
c.node().put(newKey, newKey, value, 0, 0)
338344

339345
return nil
340346
}

0 commit comments

Comments
 (0)