Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is address of global variables the same for different runs of the program?

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?

like image 416
Tarun Gehlaut Avatar asked Jul 25 '14 09:07

Tarun Gehlaut


People also ask

Why do we generally use both local and global variables?

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.

How to access a global variable everywhere in C?

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.

How to restrict access of a global variable only to functions?

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.

What is the global reach of a variable?

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.


3 Answers

You always get the same addresses if ASLR is disabled. You get unpredictable addresses if ASLR is enabled.

like image 56
Daniel Darabos Avatar answered Nov 15 '22 04:11

Daniel Darabos


The virtual address will be whatever the linker decided. The physical address will vary with each load.

like image 21
user207421 Avatar answered Nov 15 '22 03:11

user207421


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!

like image 40
Klaus Avatar answered Nov 15 '22 04:11

Klaus