veandco / go-sdl2

SDL2 binding for Go
https://godoc.org/github.com/veandco/go-sdl2
BSD 3-Clause "New" or "Revised" License
2.2k stars 218 forks source link

Unsafe uses of pointers to first slice element #383

Closed gonutz closed 5 years ago

gonutz commented 5 years ago

There are some places in the code where a pointer to the first element of a slice is used but there is no check if they really exist. Here are the places I found:

Renderer.DrawLines Renderer.DrawPoints Renderer.DrawRects Renderer.FillRects Sensor.GetData Surface.FillRects Texture.Update Texture.UpdateRGBA Texture.UpdateYUV and here and here Window.UpdateSurfaceRects

The code there looks like this

func (sensor *Sensor) GetData(data []float32) (err error) {
    _data := (*C.float)(unsafe.Pointer(&data[0]))
    // ...
}

where data[0] is accessed even though len(data) might be zero. This would panic at runtime which is always bad so I propose to change these occurrences to the analogues of this:

func (sensor *Sensor) GetData(data []float32) (err error) {
    if data == nil {
        return nil // getting no data always works fine
    }
    _data := (*C.float)(unsafe.Pointer(&data[0]))
    // ...
}

I have done this in my DLL-only-on-Windows fork.