[英]What happens in the backend when you initialize a variable on the stack in C?
When I declare a variable int b;
当我声明一个变量
int b;
what actually happens in the backend?后端实际发生了什么? Would it translate to
int* b = malloc(sizeof(int))
, just that it will be bound by a scope?它会转化为
int* b = malloc(sizeof(int))
,只是它会被 scope 绑定吗? I understand that a variable on the stack is bound by a scope and the heap is not necessarily bound by a scope, but on the backend, is the allocation similar?我知道堆栈上的变量由 scope 绑定,而堆不一定由 scope 绑定,但在后端,分配是否相似? Hopefully I explained it well enough for someone to correct me
希望我解释得很好,有人能纠正我
Most CPUs have a register that functions as a "stack pointer" for the running thread;大多数 CPU 都有一个寄存器,用作正在运行的线程的“堆栈指针”。 it always points to the "top" of the thread's stack.
它始终指向线程堆栈的“顶部”。 Whenever a new stack object needs to be created, the object is initialized at the address the stack-pointer is currently pointing to, and then the stack-pointer's value is increased by the size of the object.
每当需要创建新的堆栈 object 时,object 会在堆栈指针当前指向的地址处初始化,然后堆栈指针的值会增加 ZA8CFDE6331BD59EB2666F8911ZC4 的大小。
Similarly, after a stack-object has been destroyed (because execution is leaving the current scope), the stack-pointer is decreased by the size of the object.类似地,在堆栈对象被销毁后(因为执行正在离开当前范围),堆栈指针会减少 object 的大小。
That's really all there is to it;这就是它的全部。 it's much simpler and more efficient than manipulating the heap.
它比操作堆更简单、更有效。 The only downside is that space has to be initialized and de-initialized in strict FILO order -- ie objects have to be destroyed in the opposite order from how they were constructed.
唯一的缺点是空间必须按照严格的 FILO 顺序进行初始化和取消初始化——即对象必须按照与它们的构造方式相反的顺序被销毁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.