返回堆栈上的指针 [英] Returning a pointer on stack

查看:75
本文介绍了返回堆栈上的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中,当我从函数返回堆栈创建的变量的指针时,在函数返回后内存将被丢弃,从而使指针无法取消引用.但是在Go中,编译器没有给我任何错误.这是否意味着这样做是安全的?

In C when I return a pointer of a stack-created variable from a function, the memory discards after the function is returned, thus making the pointer impossible to dereference. But in Go, the compiler is not giving me any errors. Does that mean that this is safe to do?

package main

import (
    "fmt"
)

func main() {
    fmt.Println(*(something()))
}

func something() *string {
    s := "a"
    return &s
} 

推荐答案

是的,这是安全的,并且是Go编程中的常规模式. Go使用转义分析来移动带有指针的任何值,这些指针会自动将堆栈转义到堆中.您不必担心分配值的位置.

Yes, this is safe and a normal pattern in Go programming. Go uses escape analysis to move any values with pointers that escape the stack to the heap automatically. You don't need to be concerned with where values are allocated.

从Go常见问题解答中:>我如何知道在堆还是堆栈上分配了变量? "

From the Go FAQ: "How do I know whether a variable is allocated on the heap or the stack?"

如果编译器无法证明函数返回后未引用该变量,则编译器必须在垃圾回收堆上分配该变量,以避免悬空指针错误

if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors

您可以使用-gcflags -m选项在编译过程中看到这些优化选择.

You can see these optimization choices during compilation by using the -gcflags -m option.

这篇关于返回堆栈上的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆