go
runtime_error
ai_generated
true
panic: runtime error: slice bounds out of range
ID: go/unsafe-string-conversion
80%Fix Rate
86%Confidence
0Evidence
2024-08-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.20 | active | — | — | — |
Root Cause
Converting a `[]byte` to `string` using `unsafe` without ensuring proper length, leading to out-of-bounds read.
generic中文
使用`unsafe`将`[]byte`转换为`string`时未确保正确长度,导致越界读取。
Workarounds
-
100% success Use `string(b)` for safe conversion (copies)
s := string(b) // s is immutable copy
-
80% success Use `unsafe.String` with explicit length (Go 1.20+)
s := unsafe.String(&b[0], len(b)) // but ensure b is not mutated
Dead Ends
Common approaches that don't work:
-
Using `*(*string)(unsafe.Pointer(&b))` directly
90% fail
String header may have wrong length if slice header changes.
-
Assuming zero-copy is always safe
70% fail
If slice is modified later, string becomes invalid.