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 关于vmprotect3.8.4虚拟文件一项
  • ¥15 在不用IT调试的情况下怎样能连外网
  • ¥20 C#调用虚拟键盘TabTip.exe
  • ¥15 Qt4代码实现下面的界面
  • ¥15 CCS离散化传递函数与仿真不一致
  • ¥15 prism提示我reinstall prism 如何解决
  • ¥15 asp.core 权限控制怎么做,需要控制到每个方法
  • ¥20 while循环中OLED显示中断中的数据不正确
  • ¥15 这个视频里的stm32f4代码是怎么写的