# How does dynamic memory-allocation exactly work?

I have wondered about ordinary code. Assume we are running this code on any modern System like Unix/Linux/Mac/Windows. This code is C, but it should work with every language which is close to the hardware.

int a = 8;
//printf("%d", (int)&a);


This will show obviously that the system allocated the int dynamically. So there is no static address used. Now we continue by:

a = a+1;


Now, my question follows:

Since the address to "a" is allocated dynamically, we need presumably a pointer which points to a pointer pointing to "a". But how do we store this pointer? We would again need a dynamically allocated address and would, therefore, pass the problem. So, in my mind, we need static addresses the program can use, but how does the process know these addresses?

How does the process store its own allocations, so that after initializing a variable, the process knows what the variable actually is or at least where the variable was allocated?

If this question is not clear enough, please comment below.

Thank you!

• I believe that $a$ would be stored on the stack, at a known offset from the top-of-stack. Jun 10, 2019 at 13:55
• I'm not sure what you mean by "profound code". It seems you meant some word other than "profound" ("very great or intense", "having or showing great knowledge or insight") but I can't work out what. Jun 10, 2019 at 14:58
• Yes, in German "profan" means "profane", not "profound". Thank you! Jun 10, 2019 at 15:34
• I'm not sure what you mean by "profane code", either. "Profane" means not sacred, or not respectful of sacred things. Jul 10, 2019 at 16:10
• @TVSuchty Not in any kind of common usage, no. I doubt many people would understand it to mean that. Jul 11, 2019 at 14:49

Consider the following code:

int a = 8;
a = a+1;


On my system, this snippet compiles to the following code:

movl    $$8, -20(%rbp) movl -20(%rbp), %edi addl$$1, %edi
movl    %edi, -20(%rbp)


The register rbp points at the top of stack. The variable a is located 20 bytes below the top of stack.

The first assembly line about implements the C line int a = 8, and the rest implement a = a+1 by first loading a into the register edi, then increasing edi by 1, and then storing edi back at a.

If you want to try it out, use the following command:

cc -O0 -S <progname>.c


The assembly will appear in <progname>.s.

• So how do you know where the stack is located? Jun 10, 2019 at 15:32
• In the x86 architecture, the register rsp points at the top of stack. Part of the C code I skipped copied rsp to rbp. Jun 10, 2019 at 17:45
• So the processor know where the stack is located? Jun 11, 2019 at 7:38
• The processor maintains the stack (to some extent), at least in the x86 architecture. Jun 11, 2019 at 9:40