I have the following code:
type box struct {
val int
}
var p *box
This works fine:
p = &box{val: 2}
But this results in error:
*p = box{val: 2}
Error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x5e59d9]
Why does the 2nd form of assignment result in panic?
Because p
points to nothing (nil
). You must first allocate some memory and make p
point to it before being allowed to deference p
. You can use the new
builtin to allocate memory initialised to the zero value of the pointed type.
p = &box{val: 2}
has the same result as:
p = new(box)
*p = box{val: 2}
Because the pointer is not pointing anything. It's value is null. If it pointed to something, then you could try to change the thing which is being pointed at.
p = &box{val: 2}
Before this statement, p = nil, after this statement, p = some memory address.
*p = box{val: 2}
Before this statement, if p = nil, you'll get an error, because you're trying to set value, of address which is stored in variable p. It basically tries to get something from nil address.
If you did that:
p = &box{val: 2}
*p = some new value
It would work fine, because p already points to some address and you can change value on that address.