douji7399 2015-08-11 07:40
浏览 63
已采纳

在Go中使用unsafe.Pointer进行恐慌

The code is:

package main

import (
    "fmt"
    "unsafe"
)

type Point struct {
    x int 
    y int 
}

func main() {

    buf := make([]byte, 50) 
    fmt.Println(buf)
    t := (*Point)(unsafe.Pointer(&buf))
    t.x = 10
    t.y = 100 
    fmt.Println(buf)
}

When running it, a run-time panic occurs:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0xa pc=0x43dd4d]

Why?

  • 写回答

1条回答 默认 最新

  • douweida2669 2015-08-11 07:44
    关注

    Because buf is a slice (not an array), and slices are just descriptors.

    You most likely wanted to write to the memory space of the allocated bytes, so instead of using the address of the slice descriptor, use the address of the allocated bytes, which you can get by taking the address of the first element (a slice describes a contiguous section of an underlying array):

    t := (*Point)(unsafe.Pointer(&buf[0]))
    

    Output (try it on the Go Playground):

    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
    [10 0 0 0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
    

    As you can see, data you set appears in the 2nd output (10 0 0 0 are the 4 bytes of the int value 10, 100 0 0 0 are the 4 bytes of the int value 100).

    You see panic if you use the address of the slice descriptor because the descriptor contains things like the address of the first element, the element count and capacity. So by using the address of the descriptor you will modify these and when trying to print it again as a slice, the data you wrote to it will most likely be in invalid pointer. This is confirmed by you writing the value 10 which is 0xa in hex and the error message contains: addr=0xa

    Another option would be to use a "real" array instead of a slice because arrays are not descriptors:

    buf := [50]byte{}
    t := (*Point)(unsafe.Pointer(&buf))
    

    And with this change the output will be the same.

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

报告相同问题?

悬赏问题

  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL