Reputation: 139
In C you can use the function write()
from the unistd.h
library.
write()
is faster than printf()
, and allows you to write to the standard output (or a file) before a Segfault breaks your code.
When debugging, I wish to write to the standard output before my Go code panics. In general, how do I do that?
I have the following code (to find the shortest word in a string of words) which is panicking and I want to isolate where, by inserting write methods.
func FindShort(s string) int {
i := 0
j := 0
min := math.MaxInt32
for true {
for s[i] == ' ' {
i++
j++
}
for s[j] != ' ' && j < len(s) {
j++
}
if j > i && (j - i) < min {
min = j - i
}
i = j
if j == len(s) {
break
}
}
return min
}
Upvotes: 1
Views: 285
Reputation: 763
you could use a defered function that calls the recover function, the function below will result in "Recovered panic here"
defer func() {
r := recover()
if r != nil {
fmt.Println("Recovered", r)
}
}()
panic("panic here")
Upvotes: 1
Reputation: 320
Your code checks all lines if it contains a space, but it isn't checking if the line ends (end of line / end of file / line feed). There is a easier way to check what the shortest word is :
package main
import (
"fmt"
"math"
"strings"
)
func main() {
min := math.MaxInt32
shortest := math.MaxInt32
s := strings.Split("this is a test", " ")
for key, value := range s {
if len(value) < min {
min = len(value)
shortest = key
}
}
fmt.Print(s[shortest])
}
Upvotes: 0