dongleman4760 2019-01-11 09:15
浏览 135
已采纳

尝试复制时的boltdb意外故障地址

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
", lastSth, lastSth)
        lastSthCopy = make([]byte, len(lastSth))
        copy(lastSth, lastSthCopy) // this line fails.
        fmt.Printf("lastSth:%s@%p, lastSthCopy:%p
", 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.

  • 写回答

1条回答 默认 最新

  • douzhi4056 2019-01-11 12:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度