在两个不同的函数中使用具有相似变量的指针。

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

pointers with two similar variables in two different functions

问题

我在两个不同的函数中有两个变量名相似的变量,并且在这些变量内部,我使用 & 来获取变量的地址。

问题是:是否可能获取到第二个函数内部变量的内存地址?

英文:

I have 2 variables with similar names in two different functions and inside of them I get variable's address using &.

Question is: is it possible that it will get a memory address of a variable inside the second function

答案1

得分: 2

如果这些函数不相互调用,那么当调用其中一个函数时,地址可能是x,然后如果该函数返回(且变量没有逃逸),并且调用另一个函数时,相同的x地址可能会被重用;但前提是另一个变量不再是“活动的”(可访问的)。根据你的问题,无法确定是否会出现这种情况。

Go语言具有自动内存管理。除非涉及unsafe包,否则不必担心指针和地址,可以安全地获取并返回局部变量的地址。如果仍然可以访问使用该内存的变量,则不会重新使用相同的内存。

一个例外是大小为0的变量。根据规范,大小为零的变量可能具有相同的地址,也可能没有。实际上,这不会引起任何问题,因为你无法更改这些变量的值,它们无法存储不同的值,但是你不能对它们的内存地址做任何假设。

英文:

If those functions do not call each other, it's possible that calling one, the address will be x, then if the function returns (and the variable does not escape) and the other function is called, the same x address may be reused; but only if the other variable is not live (reachable) anymore. Whether this may be the case is not clear from your question.

Go has automatic memory management. Unless you touch package unsafe, you should not worry about pointers and addresses, it's safe to take and even to return addresses of local variables. The same memory will not be reused if a variable using that memory is still reachable.

One exception is variables that have 0 size. As per the spec, variables having zero size may or may not have the same address. In practice this causes no trouble as you can't change the value of such variables as they cannot store different values, but you can't assume anything about their memory addresses.

huangapple
  • 本文由 发表于 2021年7月24日 20:35:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/68510013.html
匿名

发表评论

匿名网友

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

确定