Stack variables in go?

huangapple go评论83阅读模式
英文:

Stack variables in go?

问题

以下是代码的中文翻译:

package main

import (
  "fmt"
  "os"
)

func main() {
  var l = test(4)
  test(5)
  fmt.Fprintf(os.Stdout, "%d\n", *l)
}

func test(v int) *int {
  var p = v
  return &p
}

在C语言中,等效的代码会打印出5,因为第一个栈帧中的变量p会被第二个栈帧中的相同变量p覆盖。我反汇编了这段代码,但对其意义并不能理解太多。

#include <stdio.h>

int* test(int v);
int main() {
    int* p = test(4);
    test(5);
    printf("%d\n", *p);
}

int* test(int v) {
    int p = v;
    return &p;
}

有人能给我一个关于Go语言内存管理工作原理的基本概述吗?函数变量是否存放在堆上?

英文:
package main

import (
  &quot;fmt&quot;
  &quot;os&quot;
)

func main() {
  var l = test(4)
  test(5)
  fmt.Fprintf(os.Stdout, &quot;%d\n&quot;, *l)
}

func test(v int) *int {
  var p = v
  return &amp;p
}

In C, the equivalent code would print 5 because the the variable p in the first stack frame would be overwritten by the same variable p in the second stack frame. I disassembled the code but am not able to make too much sense of it.

#include &lt;stdio.h&gt;                                                                                                                                                                                                                                                                                                           

int* test(int v); 
int main() {
    int* p = test(4);
    test(5);
    printf(&quot;%d\n&quot;, *p);
}

int* test(int v) {
    int p = v;
    return &amp;p; 
}

Can somebody give me a basic synopsis of how memory management works in Go? Do function variables go on the heap?

答案1

得分: 1

这是一段关于逃逸分析的内容。逃逸分析在官方文档中并不完善,但你可以参考这个链接:http://blog.rocana.com/golang-escape-analysis

你可以使用以下命令对你的代码进行逃逸分析(假设你的文件名是main.go):

go run -gcflags '-m -l' main.go
英文:

It is somewhat strange that we don't have good official documentation on escape analysis (or maybe even if it's there I haven't found it yet!) but here's something I found useful : http://blog.rocana.com/golang-escape-analysis

You can use something like this to do an escape analysis for your code (assuming your filename is main.go):

go run -gcflags &#39;-m -l&#39; main.go

huangapple
  • 本文由 发表于 2017年9月16日 04:30:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/46247086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定