Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading