0

I have the following program.

package main

import (
    "fmt"
    "log"

    "github.com/boltdb/bolt"
)

const dbFile = "testbolt.db"
const testBucket = "test"

func main() {
    db, err := bolt.Open(dbFile, 0600, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    err = db.Update(func(tx *bolt.Tx) error {
        _, err := tx.CreateBucketIfNotExists([]byte(testBucket))
        if err != nil {
            return err
        }
        return nil
    })
    if err != nil {
        log.Fatal("1", err)
    }

    err = db.Update(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte(testBucket))
        err := b.Put([]byte("l"), []byte("writesomething"))
        return err
    })
    if err != nil {
        log.Fatal("2", err)
    }

    var lastSth []byte
    var lastSthCopy []byte
    err = db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte(testBucket))
        lastSth = b.Get([]byte("l"))
        fmt.Printf("lastSth %s@%p\n", lastSth, lastSth)
        lastSthCopy = make([]byte, len(lastSth))
        copy(lastSth, lastSthCopy) // this line fails.
        fmt.Printf("lastSth:%s@%p, lastSthCopy:%p\n", lastSth, lastSth, lastSthCopy)

        return nil
    })
    if err != nil {
        log.Fatal("3", err)
    }
}

While printing the address and value of the lastSth byte slice is fine, copying the value to another byte slice gives the following error.

lastSth writesomething@0xc94055
unexpected fault address 0xc94055
fatal error: fault
[signal 0xc0000005 code=0x1 addr=0xc94055 pc=0x4549de]

Please advise.

3tbraden
  • 667
  • 1
  • 10
  • 21
  • 1
    There is an [issue](https://github.com/boltdb/bolt/issues/204) in BoltDb Github page. Have you seen it? Your problem cannot be reproduced by arbitrary byte slice copying directly anyway: https://play.golang.org/p/cYCscNE8FDW – vahdet Jan 11 '19 at 09:32
  • yes I have seen that, but I believe that issue concerns reference outside the transaction while the problem here happens inside the transaction, and I am pretty sure the above code can reproduce the problem(at least I got it every time) – 3tbraden Jan 11 '19 at 09:43

1 Answers1

3

Check out the signature for copy():

func copy(dst, src []Type) int

You currently have:

copy(lastSth, lastSthCopy) // copies lastSthCopy (src) to lasSth (dst)

I think you have the dst and src backwards. You probably meant:

copy(lastSthCopy, lastSth)

This fixes the error. Copying your []byte into bolt's []byte was causing the memory fault.

blobdon
  • 1,176
  • 7
  • 11