go system_error ai_generated true

error: cgo: C function returned error: errno 2

ID: go/cgo-errno-handling

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.19 active

Root Cause

C function sets `errno` on failure, but Go code does not check it, leading to silent failures.

generic

中文

C函数在失败时设置`errno`,但Go代码未检查,导致静默失败。

Workarounds

  1. 90% success Check return value and use `C.CString` to get error message
    ret := C.someCFunction()
    if ret != 0 {
        errno := C.errno
        errStr := C.GoString(C.strerror(errno))
        return fmt.Errorf("C error: %s", errStr)
    }
  2. 80% success Use `cgo.Handle` to capture error in a thread-safe way
    // Not directly applicable; use mutex to protect errno reading

Dead Ends

Common approaches that don't work:

  1. Ignoring the return value of C function 90% fail

    No error handling at all.

  2. Using `C.errno` directly without thread safety 60% fail

    errno is thread-local in C, but Go may not preserve it.