Search code examples
pointersgodereferencepanic

Using xlsx package panic: runtime error: invalid memory address or nil pointer dereference Go


var(    
    file            *xlsx.File
    sheet           *xlsx.Sheet
    row             *xlsx.Row
    cell            *xlsx.Cell
)

func addValue(val string) {     
        cell = row.AddCell()
        cell.Value = val
}

and imported from http://github.com/tealeg/xlsx

when ever control comes to this line

cell = row.AddCell()

It is panicking. error:

panic: runtime error: invalid memory address or nil pointer dereference

Can someone suggest whats going wrong here?


Solution

  • Nil pointer dereference

    If to attempt to read or write to address 0x0, the hardware will throw an exception that will be caught by the Go runtime and panic will be throwed. If the panic is not recovered, a stack trace is produced.

    Definitely you are trying to operate with nil value pointer.

    func addValue(val string) {
        var row *xlsx.Row // nil value pointer
        var cell *xlsx.Cell
        cell = row.AddCell() // Attempt to add Cell to address 0x0.
        cell.Value = val
    }
    

    Allocate memory first

    func new(Type) *Type:

    It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is, new(T) allocates zeroed storage for a new item of type T and returns its address, a value of type *T. In Go terminology, it returns a pointer to a newly allocated zero value of type T.

    Use new function instead of nil pointers:

    func addValue(val string) {
        row := new(xlsx.Row)
        cell := new(xlsx.Cell)
        cell = row.AddCell()
        cell.Value = val
    }
    

    See a blog post about nil pointers