For this code:
int main(void) {
int a = 1;
int b = 2;
int* pa = &a;
*pa = a + b;
printf("%d", a);
}
At compile time the compiler calculates how much space it needs. We have 2 integers and one pointer. So it is 2*4 + 8 = 16. Then it specifies where the memory of a given variable is in relation to the start point address.
pa is at the start point address and have length of 8 bytes.
b is at start point address + 8 bytes and have length 4 bytes.
a is at start point address + 12 bytes and have length 4 bytes.
Then go instructions for execution time:
- Ask OS to allocate 16 bytes and provide address for that space in memory. This will be start point address.
- put the binary representation of
1at the location ofa. - put the binary representation of
2at the location ofb. - translate relative address of
a(start point address + 12 bytes) to its absolute location and put it at location ofpa. - get bytes at location
aand bytes at locationb, add them and then get bytes at locationpa. Use bytes at locationpaas an address and put there the calculated sum. - print the bytes at location
aconverting them to decimal number first. - free memory and let the OS know that program finished.
Is this a valid translation?
edit:
Let's assume a super simple compiler is used (no optimizations). All it cares about is a valid execution of C code.