cmemory-managementinstructionsprocessing-instruction

is my translation C code to instructions for CPU correct?


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:

  1. Ask OS to allocate 16 bytes and provide address for that space in memory. This will be start point address.
  2. put the binary representation of 1 at the location of a.
  3. put the binary representation of 2 at the location of b.
  4. translate relative address of a (start point address + 12 bytes) to its absolute location and put it at location of pa.
  5. get bytes at location a and bytes at location b, add them and then get bytes at location pa. Use bytes at location pa as an address and put there the calculated sum.
  6. print the bytes at location a converting them to decimal number first.
  7. 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.


Solution

  • As far as I read, yes it is a valid translation. No, it is almost 100 % certainly not the translation your compiler is going to produce. The C standard has the so-called as-if rule which means the compiler is free to produce any program whose side effects are as if the program were compiled for the so-called abstract C machine and run in there.

    In practice, a compiler could for example produce the following program:

    To an observer, the side effects of this program would be indistinguishable from those of your program: it prints 3 and returns from main with 0 as return value.