globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 230 forks source link

invalid memory address or nil pointer dereference #261

Closed sedgwickz closed 5 years ago

sedgwickz commented 6 years ago

In the main function, defer xxx().Close() reported panic error, that xxx was a function which returns the *mgo.Session pointer. I was not sure what happened.

The directory structure as below:

├── db
│   ├── db.go  (return the *mgo.Seesion by xxx public function)
│   └── import.go
└── main.go (use defer xxx.Close())
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x11db3f6]

goroutine 1 [running]:
github.com/globalsign/mgo.(*Session).Close(0x0)
        /Users/sedgwickz/Documents/golang/src/github.com/globalsign/mgo/session.go:2059 +0x26
main.main()
        /Users/sedgwickz/Documents/golang/src/github.com/grewords/main.go:17 +0x94
exit status 2
maitesin commented 6 years ago

Hi @sedgwickz,

Thanks for reporting this issue. We might need some more information about the problem in order to help you. Can you provide a snippet of code that can reproduce this issue? Moreover, what is the version of Go, mgo you are using? And in which operating system are you having this issue.

Oscar

sedgwickz commented 6 years ago

Hi @maitesin

Thank you for your reply. I have made a demo program to indicate my problem, but not sure if there is something wrong with mgo or by my own ill used. I think you can check and review my code to find some clues. And related information is as below, but I am sure how to find the mgo version.

go1.10.2 darwin/amd64

testMGO.zip

Sayan- commented 5 years ago

Hi @sedgwickz

There is a scope issue in db/db.go:

func init() {
    log.Println("db initial...")
    session, err := mgo.Dial("mongodb://127.0.0.1:27017")
    if err != nil {
        panic(err)
    }
    database = session.DB("testdb")
}

session is being shadowed in init. You can rewrite init as:

func init() {
    var err error
    log.Println("db initial...")
    session, err = mgo.Dial("mongodb://127.0.0.1:27017")
    if err != nil {
        panic(err)
    }
    database = session.DB("testdb")
}

to get your expected behavior

domodwyer commented 5 years ago

Hi @sedgwickz

@Sayan- nailed it (nice!) so I'm going to close this.

Dom