go runtime_error ai_generated true

恐慌:运行时错误:cgo参数包含指向Go指针的Go指针

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-01-05首次发现

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率 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% 成功率 Manually append null byte and pin
    b := []byte("hello\x00")
    C.printString((*C.char)(unsafe.Pointer(&b[0])))

无效尝试

常见但无效的做法:

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

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

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

    Go string data is not null-terminated.