Question

I'm having simple code as follows:

#include<stdio.h>

int glob;

int main(void)
{
   int a;
   printf("&a is : %p \n", &a);
   printf("glob is : %p \n", &glob);
   return 0;
}

Output of above program is: First run:

&a is : 0x7fff70de91ec
glob is : 0x6008f4

Second run :

&a is : 0x7fff38c4c7ac
glob is : 0x6008f4

I'm studying about virtual & physical addresses. I have following question:

  1. Which is the printed address(physical/virtual) of variable "a"?
  2. If it is virtual then, How it changes in each run of same program? As i understood compiler provides virtual address to variables at compile time?
  3. Why the address of global variable is constant in each run of program?

In executed this program on Linux : 2.6.18-308.el5 x86_64 GNU/Linux

Compiled using : gcc version 4.1.2 20080704 (Red Hat 4.1.2-52)

Was it helpful?

Solution 2

Addresses seen in a program are always virtual and the behaviour described by the OP is a Linux counter-measure to avoid buffer overflow attacks.

Just to try, you can disable it with

sysctl -w kernel.randomize_va_space=0

then run again your program and watch.

The global one is in another space of memory that can't be harmful in an hackish-wise point of view. That's because it is not randomized every time.

OTHER TIPS

Both addresses are virtual.

Modern systems uses stack randomization to prevent so-called stack-smashing attacks, which is why the local variable can change its location every run. However the global variable is stored in the executable and is loaded at the same offset every time.

Your program will always see just virtual address.

Real addresses are available only of virtual memory manager in kernel mode.

Globals has same address (until you place other variables before it) because it is created in data segment.

Local variables are always created on stack.

All the addresses seen by program are virtual. However local variables go on stack and global on special area called Data segment. Though variables relative locations are decided at compilation , stack may vary on each run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top