在Golang中,将元素推回到向量(vector)中导致程序崩溃。

huangapple go评论88阅读模式
英文:

pushback to vector in Golang causes program crash

问题

func extract_word(r rune) bool {
    return !unicode.IsLetter(r)
}

type kv_string_value struct {
    str string
    num int
}

func Map(value string) *list.List {

    t := strings.FieldsFunc(value, extract_word)
    fmt.Println("t:", len(t))
    m := make(map[string]int)
    for _, word := range t {
        m[word]++
    }
    var x *list.List

    for k, v := range m {
        pair := kv_string_value{}
        pair.str = k
        pair.num = v
        x.PushBack(pair)
        fmt.Println("Good5")
    }

    return x
}

这段代码中的问题在于 x 是一个指向 list.List 的指针,但是它没有被初始化。因此,在调用 x.PushBack(pair) 时会导致空指针解引用错误。你需要在使用 x 之前先对其进行初始化,可以使用 x := list.New() 来创建一个新的 list.List 对象。这样就可以正常地将 pair 添加到列表中了。

英文:
func extract_word(r rune) bool {
    return !unicode.IsLetter(r)
}
type kv_string_value struct {
    str string
    num int
}

func Map(value string) *list.List {

	t := strings.FieldsFunc(value, extract_word)
        fmt.Println("t:", len(t))
        m := make(map[string]int)
	for _, word  := range t{
        	m[word]++	
	}
	var x *list.List
        
        for k,v := range m {
		pair := kv_string_value{}
                pair.str = k
                pair.num = v
		x.PushBack(pair)
		fmt.Println("Good5")
	}
        
	return x
}

Something wrong with this "x.PushBack(pair)"

it just pushback a pair to a list, why it crash my program?
need help.
thanks!

  /main$ go run wc.go master kjv12.txt sequential
    # command-line-arguments
    ./wc.go:34: *x.PushBack(pair) evaluated but not used
  main$ go run wc.go master kjv12.txt sequential
    Split kjv12.txt
    name is mrtmp.kjv12.txt-0
    DoMap: read split mrtmp.kjv12.txt-0 966967
    Read succesful.
    t: 160040
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal 0xb code=0x1 addr=0x0 pc=0x444c25]
    
    goroutine 1 [running]:
    runtime.panic(0x6874a0, 0x9c5a48)
    	/usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
    container/list.(*List).lazyInit(0x0)
    	/usr/lib/go/src/pkg/container/list/list.go:86 +0x5
    container/list.(*List).PushBack(0x0, 0x68ce20, 0xc210084240, 0x2)
    	/usr/lib/go/src/pkg/container/list/list.go:138 +0x27

答案1

得分: 6

错误出在:

var x *list.List

你声明了一个指向 list.List 的指针,但没有创建实例。x 的初始值将为 nil。要使你的代码正常工作,将该行改为:

x := list.New()
英文:

The bug lies in:

var x *list.List

You declare a pointer to a list.List without creating an instance of it. x will have the initial value of nil. To make your code work, change the line to:

x := list.New()

huangapple
  • 本文由 发表于 2014年5月16日 12:06:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/23692471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定