Stack variables in go?

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

Stack variables in go?

问题

以下是代码的中文翻译:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. var l = test(4)
  8. test(5)
  9. fmt.Fprintf(os.Stdout, "%d\n", *l)
  10. }
  11. func test(v int) *int {
  12. var p = v
  13. return &p
  14. }

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

  1. #include <stdio.h>
  2. int* test(int v);
  3. int main() {
  4. int* p = test(4);
  5. test(5);
  6. printf("%d\n", *p);
  7. }
  8. int* test(int v) {
  9. int p = v;
  10. return &p;
  11. }

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

英文:
  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;os&quot;
  5. )
  6. func main() {
  7. var l = test(4)
  8. test(5)
  9. fmt.Fprintf(os.Stdout, &quot;%d\n&quot;, *l)
  10. }
  11. func test(v int) *int {
  12. var p = v
  13. return &amp;p
  14. }

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.

  1. #include &lt;stdio.h&gt;
  2. int* test(int v);
  3. int main() {
  4. int* p = test(4);
  5. test(5);
  6. printf(&quot;%d\n&quot;, *p);
  7. }
  8. int* test(int v) {
  9. int p = v;
  10. return &amp;p;
  11. }

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):

  1. 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):

  1. 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:

确定