go
runtime_error
ai_generated
true
恐慌:运行时错误:切片索引越界
panic: runtime error: slice bounds out of range
ID: go/unsafe-string-conversion
80%修复率
86%置信度
0证据数
2024-08-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.20 | active | — | — | — |
根因分析
使用`unsafe`将`[]byte`转换为`string`时未确保正确长度,导致越界读取。
English
Converting a `[]byte` to `string` using `unsafe` without ensuring proper length, leading to out-of-bounds read.
解决方案
-
100% 成功率 Use `string(b)` for safe conversion (copies)
s := string(b) // s is immutable copy
-
80% 成功率 Use `unsafe.String` with explicit length (Go 1.20+)
s := unsafe.String(&b[0], len(b)) // but ensure b is not mutated
无效尝试
常见但无效的做法:
-
Using `*(*string)(unsafe.Pointer(&b))` directly
90% 失败
String header may have wrong length if slice header changes.
-
Assuming zero-copy is always safe
70% 失败
If slice is modified later, string becomes invalid.