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)&amp;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!
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 &lt;progname&gt;.c


The assembly will appear in &lt;progname&gt;.s.