Search code examples
pointersgosliceunsafe

Panic using unsafe.Pointer in Go


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?


Solution

  • 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.