Home > Net >  What happens in the backend when you initialize a variable on the stack in C?
What happens in the backend when you initialize a variable on the stack in C?

Time:11-20

When I declare a variable 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? 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? Hopefully I explained it well enough for someone to correct me

CodePudding user response:

Most CPUs have a register that functions as a "stack pointer" for the running thread; 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.

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.

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 -- i.e. objects have to be destroyed in the opposite order from how they were constructed.

  • Related