gosegmentation-faultboltdb

boltdb unexpected fault address when trying to copy


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.


Solution

  • 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.