函数变量的内存分配 [英] Memory Allocation for Function Variables

查看:63
本文介绍了函数变量的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我对C ++编译器工作的调查中,我保持

看到函数变量被释放后的参考

执行后。这是在堆栈或堆级别上的释放吗?

是否存在堆栈中的动态变量? (从编译器的角度来看)



谢谢

Throughout my inquiries into the workings of C++ compiler i keep
seeing the references to the fact that function variables are deallocated
after execution. Is this deallocation on stack or heap level? Is there
such a thing as dynamic variables within a stack? (from compiler''s perspective)

Thank You

推荐答案

使用C ++(以及之前的C) )所有变量都是基于堆栈的,除非它们是使用malloc(旧样式)或new(最好)直接从堆中分配的 - 在这种情况下,完成后必须使用适当的delete或free方法。



堆栈上没有动态变量这样的东西,因为所使用的函数的变量空间可以在编译时计算 - 动态分配只发生在堆上。 br />


当函数退出时,基于堆栈的变量会自动解除分配,因为堆栈随后被释放以供下一个函数使用它:



也许一个小图会有所帮助:x用于堆栈,f是免费的。 sp是堆栈指针 - 下一个可用内存

函数调用前的堆栈:

With C++ (and C before it) all variables are stack based, unless they are directly allocated from the heap with a malloc (old style) or new (preferable) - in which case you must use the appropriate delete or free method when you are finished with it.

There is no such thing as "dynamic" variables on the stack, since the variable space a function used can be calculated at compile time - dynamic allocation only happens with the heap.

Stack based variables are automatically deallocated when the function exits, because the stack is then freed for the next function to use it:

Maybe a little diagram will help: "x" is used stack, "f" is free. "sp" is the stack pointer - the next free memory
Stack before function call:
xxxxxxxxffffffffffffffff
sp------^





通话功能



Call function

xxxxxxxxRfffffffffffffff
sp-------^

现在,返回地址已经堆叠(R - 代码中调用函数的位置)并且sp已经移动到下一个免费location



函数变量

Now, the Return address has been stacked ("R" - the place in your code from which the function was called) and the sp has moved to the next free location

In function with variables

xxxxxxxxRVVVVfffffffffff
sp-----------^

变量已经在堆栈上分配(V和sp移动)



函数

The variables have been allocated on the stack ("V" and the sp moved)

After function

xxxxxxxxrvvvvfffffffffff
sp------^

sp在返回地址之前移回并且所有变量都已被释放 - 但是内存没有改变,这就是我把它们改成小写的原因。


当调用下一个函数时,同样的过程发生了重新使用。



这就是为什么挂引用是一个PITA - 如果你返回一个指向基于堆栈的变量的指针,它仍然是一个有效的指针,并且teh内存将起作用 - 但它也可以用于其他东西,最终破坏内存。

The sp has moved back before the return address and all the variables have been deallocated - but not changed in memory, which is why I changed them to lower case.

When the next function is called, the same process happens and the memory is re-used.

That is why hanging references are a PITA - if you return a pointer to a stack based variable, it is still a valid pointer, and teh memory will work - but it can also be used for something else and you end up corrupting memory.


这篇关于函数变量的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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