Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created October 20, 2018 15:27
Show Gist options
  • Save NaniteFactory/4684722cb129d3996cf2097b725a16ad to your computer and use it in GitHub Desktop.
Save NaniteFactory/4684722cb129d3996cf2097b725a16ad to your computer and use it in GitHub Desktop.
Suggesting ways to handle invalid addresses in Golang.
package main
import (
"errors"
"log"
"unsafe"
)
func foo1() (err error) {
defer func() {
r := recover()
log.Println("Recovered:", r) //
if r != nil {
err = r.(error)
}
}()
panic(errors.New("I'm a recoverable panic! Yay"))
return err
}
func foo2() (err error) {
defer func() {
r := recover()
if r != nil {
log.Println("Recovered:", r) //
err = r.(error)
}
}()
// purposely accessing the nil address.
nilptr := (*int)(unsafe.Pointer(uintptr(0x0)))
v := *nilptr
log.Println(nilptr, v)
// this is an invalid address.
someAddr := (*uintptr)(unsafe.Pointer(uintptr(0xdd7ae08)))
log.Println(someAddr)
// purposely accessing the fault address.
// this will cause:
// ```
// unexpected fault address 0xdd7ae08
// fatal error: fault
// ```
// a fatal error is different from a panic.
// unlike a panic a fatal error just terminates the entire program and can't be handled any way.
val := *someAddr
log.Println(val)
return err
}
func main() {
log.Println("foo1():")
log.Println(foo1())
log.Println("foo1() returned.")
log.Println("foo2():")
log.Println(foo2())
log.Println("foo2() returned.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment