go runtime_error ai_generated true

panic: runtime error: cgo argument has Go pointer to Go pointer

ID: go/cgo-char-array-null-termination

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-01-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Passing a Go slice or string to C as `char*` without null termination, causing C to read past bounds.

generic

中文

将Go切片或字符串作为`char*`传递给C时未添加空终止符,导致C读取越界。

Workarounds

  1. 95% success Use `C.CString` which allocates a null-terminated C string
    cs := C.CString("hello")
    defer C.free(unsafe.Pointer(cs))
    C.printString(cs)
  2. 85% success Manually append null byte and pin
    b := []byte("hello\x00")
    C.printString((*C.char)(unsafe.Pointer(&b[0])))

Dead Ends

Common approaches that don't work:

  1. Using `C.CString` but forgetting to free 40% fail

    Memory leak, but the null termination is correct; this error is about pointer nesting.

  2. Passing `&s[0]` directly 80% fail

    Go string data is not null-terminated.