Home > Enterprise >  panic: runtime error: invalid memory address or nil pointer dereference in golang
panic: runtime error: invalid memory address or nil pointer dereference in golang

Time:08-31

I run this code in my mac. I test it and it is ok. But i compile it and start it at aws ecs. I get this error

panic: runtime error: invalid memory address or nil pointer dereference

[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x55fff8]

goroutine 6 [running]:

go.sia.tech/siad/types.NewCurrency(0xc0000d5640)

/Users/jaslin.wang/go/pkg/mod/go.sia.tech/[email protected]/types/currency.go:57  0x18

There is my code. It get error when call this line 80

74 amount, _ := new(big.Int).SetString(output.Value, 10)
75
76 addr := types.UnlockHash{}
77 addr.LoadString(output.Address)
78
79 sco := types.SiacoinOutput{
80   Value:      types.NewCurrency(amount),
81   UnlockHash: addr,
82 }

There is NewCurrency function

56 func NewCurrency(b *big.Int) (c Currency) {
57 if b.Sign() < 0 {
58  build.Critical(ErrNegativeCurrency)
59 } else {
60  c.i = *b
61 }
62 return

}

There is my compile command

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build

Thanks very much!

CodePudding user response:

2022/08/30 03:30:05 output.Value is 340900000000000000000000000.000000000000000000000000000000000000000000000000000000

2022-08-30T11:30:05.726 08:00   2022/08/30 03:30:05 ok is false

2022-08-30T11:30:05.726 08:00   2022/08/30 03:30:05 amount is <nil>

sry to bother you guys. I don't know why output.Value is 340900000000000000000000000.000000000000000000000000000000000000000000000000000000. It should be 340900000000000000000000000. But i think change it to 340900000000000000000000000 will fix this issue. Thank all of you!

CodePudding user response:

You need to check whether big.SetString() actually parsed the value. Try running this code to see it happen... Presumably SetString() is not parsing your value because you're using a big.Int() and passing it a string with floating point decimals (even if they are zeroes).

package main

import (
    "fmt"
    "math/big"
)

type Currency struct {
    i big.Int
}

func main() {
    for _, v := range []string{"1234567878768376294872638", "boom!"} {
        amount, ok := new(big.Int).SetString(v, 10)
        if !ok {
            fmt.Println("Expecting this will go boom!")
        }
        x := NewCurrency(amount)
        fmt.Println(x)
    }
}

func NewCurrency(b *big.Int) (c Currency) {
    if b.Sign() < 0 {
        fmt.Printf("Error negative currency")
        panic("panicking!")
    } else {
        c.i = *b
    }
    return
}
  •  Tags:  
  • go
  • Related