go runtime_error ai_generated true

panic: runtime error: slice bounds out of range

ID: go/unsafe-string-conversion

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-08-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 100% success Use `string(b)` for safe conversion (copies)
    s := string(b)
    // s is immutable copy
  2. 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:

  1. Using `*(*string)(unsafe.Pointer(&b))` directly 90% fail

    String header may have wrong length if slice header changes.

  2. Assuming zero-copy is always safe 70% fail

    If slice is modified later, string becomes invalid.