1

I was recently asked to consider the output of the following code:

#include <iostream>
int gvar;
int main (void)
{
     cout << &gvar << endl;
     while (true);
     return 0;
}

This code is compiled and an executable is generated. If this executable in run 2 terminals in parallel. what would it print.

My reply was that it would print 2 different addresses. But on running, I found out in both the terminals same address was printed.

Can somebody explain why this is happening. I know that might be due to virtual memory but I am not able to put the pieces together.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
ShReYaNsH
  • 302
  • 2
  • 10

1 Answers1

5

It is very clearly due to virtual memory, yes.

The addresses seen by code like this are virtual. Since each process has its own table of virtual-to-physical mappings, the virtual addresses need not be unique inside each process.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • but does that mean that every time it would return same address. As in, it could have printed a totally different address which on mapping would have returned a different physical memory address. ? – ShReYaNsH May 05 '15 at 14:23
  • @ShReYaNsH Yes, it could, but those are implementation details in the operating system. It can choose to randomize the virtual addresses used, or not. – unwind May 05 '15 at 14:25
  • so what I understand is that it is merely a co-incidence that the same address is getting printed. Though seemingly same addresses will be mapped to different addresses in physical memory. Is that correct ? – ShReYaNsH May 05 '15 at 14:28
  • @ unwind Thanks for pointing to the correct question. Helped a lot ! – ShReYaNsH May 05 '15 at 14:41