Consider the following code snippet
int i=10;
int main()
{
cout<<&i;
}
Once an exe is generated for the program, will the output be the same for different runs of the program? Assume that the OS supports virtual memory
Edit:The ques is specific to global variables which are stored in data segment. Since this is the first global variable, should the address come out to be same or different?
We generally use both local and global variables for our convenience in a program that we write. So, let us look into a program that has both local and global variables.
By default, global variables are of global scope. Which means we can access a global variable everywhere in same as well as other C programs (using extern ). First let us create a C program that contains only global variables, save the below program with name global.c.
In programming, there exists situations when you want to restrict access of a global variable only to all functions of the same program. Static scope global variables has all properties of a global variable, except they are accessible only to all functions of same program. They are declared with static keyword.
It has a global reach, which means it retains its relevance over the program's lifespan. Therefore, any feature specified within the programme can access it within the programme, unless it is shadowed. Here, 'x' and 'y' are global variables. The global variable can be accessed from all functions or modules in a programme.
You always get the same addresses if ASLR is disabled. You get unpredictable addresses if ASLR is enabled.
The virtual address will be whatever the linker decided. The physical address will vary with each load.
Simple answer: It depends :-)
If your OS starts for a program always the same environment with a virtual memory range which looks always the same, the output should be always the same.
But if you run the same os on different hardware ( maybe with different amount of ram available ) it could be res ult in a different address but normally the address is also the same, independent of the hardware.
But you should NEVER expect that the result is the same! In a short: Don't think about the virtual or real address of data in your prog. This is under control from the compiler, the OS and maybe some libraries as well. So simply ignore it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With