简体   繁体   English

当您在 C 中初始化堆栈上的变量时,后端会发生什么?

[英]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.

相关问题 将垃圾值初始化为C中的某个值时会发生什么? - What happens when you initialize a junk value to something in C? 在C语言中取消引用静态变量时会发生什么情况? - What exactly happens when you dereference a static variable in C? 打印已声明但未分配的变量在C中会发生什么? - What happens in C when you print a declared, but unassigned variable? 当您取消引用后增量C时会发生什么 - What happens when you dereference a postincrement C 基本的c问题-在c中声明静态变量时会发生什么? - Basic c question - What exactly happens when you declare a static variable in c? 当您在C(和其他语言)中声明变量时,幕后会发生什么? - What happens behind the scenes when you declare a variable in C (and other languages)? 当您由于无符号的int变量类型而在c中出现无限循环时会发生什么 - What happens when you have an infinite loop in c due to an unsigned int variable type 在现有变量上调用malloc时会发生什么? - What happens when you call malloc on an existing variable? 当你移位到变量的末尾时会发生什么? - What happens when you bit shift beyond the end of a variable? 在C中,将NULL指针传递给strcmp()时会发生什么? - In C, what exactly happens when you pass a NULL pointer to strcmp()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM