在struct panics invalid memory address or nil pointer dereference
的字段上調用atomic.AddInt64,但不是當我們重新排列字段順序時;爲什麼?atomic.AddInt64導致無效的內存地址或零指針取消引用
使用這種類型:
type CountHandler struct {
c *RequestContext
count int64
}
,並呼籲atomic.AddInt64(&countHandler.count, 1)
(場c
爲零在這一點上)恐慌。但不是當我們將其改寫爲:
type CountHandler struct {
count int64
c *RequestContext
}
錯誤消失。
我想它應該是這樣,因爲Go以順序方式將數據保存在內存中,並且達到nil
值打破了這個序列(字節);但我不知道爲什麼是這樣,因爲指針應該有固定的大小nil
或其他值。
這是圍棋的x86 1.4.2在Windows &完整的錯誤信息是:
2015/02/23 12:56:44 http: panic serving [::1]:51886: runtime error: invalid memory address or nil pointer dereference
goroutine 5 [running]:
net/http.func·011()
c:/go/src/net/http/server.go:1130 +0xa8
sync/atomic.AddUint64(0x731144, 0x1, 0x0, 0x0, 0x263168)
c:/go/src/sync/atomic/asm_386.s:118 +0xc
main.(*CountHandler).ServeHTTP(0x731140, 0x263180, 0x122f6380, 0x122f62a0)
C:/Workshop/Devox/Workshop-Go/src/geoho/web/app/app.go:62 +0x42
github.com/julienschmidt/httprouter.func·001(0x263180, 0x122f6380, 0x122f62a0, 0x0, 0x0, 0x0)
C:/Workshop/Devox/Workshop-Go/src/github.com/julienschmidt/httprouter/router.go:232 +0x4c
github.com/julienschmidt/httprouter.(*Router).ServeHTTP(0x122d5d20, 0x263180, 0x122f6380, 0x122f62a0)
C:/Workshop/Devox/Workshop-Go/src/github.com/julienschmidt/httprouter/router.go:298 +0x141
net/http.serverHandler.ServeHTTP(0x122d2280, 0x263180, 0x122f6380, 0x122f62a0)
c:/go/src/net/http/server.go:1703 +0x145
net/http.(*conn).serve(0x122e01e0)
c:/go/src/net/http/server.go:1204 +0x9d8
created by net/http.(*Server).Serve
c:/go/src/net/http/server.go:1751 +0x2ce
整個源代碼(此代碼是錯誤的,我正要學習alice
):
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
"net/http"
"os"
"sync/atomic"
)
// play with alice
func main() {
c1 := alice.New(Counter, Texter).Then(nil)
router := httprouter.New()
router.Handler("GET", "/", c1)
router.GET("/kill", kill)
http.ListenAndServe(":27007", router)
}
func kill(rw http.ResponseWriter, rq *http.Request, pl httprouter.Params) {
os.Exit(0)
}
var ch CountHandler
// constructors:
func Counter(h http.Handler) http.Handler {
return &ch
}
func Texter(h http.Handler) http.Handler {
var t TextHandler
switch x := h.(type) {
case *CountHandler:
t.c = x.c
t.text = fmt.Sprintf("called so far %d", atomic.LoadInt64(&x.count))
}
return &t
}
// handlers:
type RequestContext struct {
val int
}
type CountHandler struct {
c *RequestContext
count int64
}
func (c *CountHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
atomic.AddInt64(&c.count, 1)
}
type TextHandler struct {
c *RequestContext
text string
}
func (t *TextHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(t.text))
}
看起來像一個bug給我。我把你的代碼和Linux上運行得很好。在操場上也一樣。看到這個:http://play.golang.org/p/fDFaZPi3nf這個確切的代碼崩潰在你的Windows機器上? – 2015-02-23 09:25:07
是的,它應該工作。請發佈更多代碼,例如你如何創建你的'countHandler'變量。請瞄準[MCVE](http://stackoverflow.com/help/mcve)。 – icza 2015-02-23 09:26:15
謝謝;我已經添加了代碼。 – 2015-02-23 09:32:09