douzhan6474 2017-02-13 16:43
浏览 13
已采纳

使用不安全的方法将[] byte转换为字符串时,“容量”存储器会发生什么情况?

I have seen people use unsafe.Pointer to efficiently convert a []byte to a string. https://play.golang.org/p/uz84H54VM8

var b = []byte{'f', 'o', 'o', 'b', 'a', 'r'}
var s = *(*string)(unsafe.Pointer(&b))

I understand what it is doing as well as the dangers involved in general but have a question about the memory.

Since the structure of a slice has a data pointer, a length, and a capacity, but the string doesn't have the capacity, what happens to that memory if b was created on the heap? Does the garbage collector know that it needs to track the capacity separately? Or could this cause a memory leak?

EDIT:

I understand how to reslice strings and slices. The above code is for when you need to convert from []byte to string but want to avoid a full copy.

The question is about the capacity that we're dropping from the structure and if it causes GC problems.

  • 写回答

1条回答 默认 最新

  • dongyan3853 2017-02-13 16:48
    关注

    The statement var s = *(*string)(unsafe.Pointer(&b)) copies the data and length from a slice header value to a string header value.

    The statement does not change the runtime's interpretation of the slice header. The capacity is not dropped from the slice header.

    Copying the data and length only does not cause GC problems.

    • The string header and slice header values are both valid after the copy operation.
    • The garbage collector does not assume that the size of a string backing array is equal to the length in the string header. For example, the GC handles the safe code s := "foobarxxx"[:6] where the string header s has length 6 and the backing array has size 9.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用