Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the address printed by printf() with a %p format in c?

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)

like image 928
BSalunke Avatar asked Apr 05 '13 11:04

BSalunke


People also ask

What is %P in C printf?

In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data.

How do you do %p in printf?

By using '%p' you print the address of the variable in question, "The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx)."

What is %P and %U in C?

Difference between %p and %x in C/C++The %p is used to print the pointer value, and %x is used to print hexadecimal values. Though pointers can also be displayed using %u, or %x. If we want to print some value using %p and %x then we will not feel any major differences.


1 Answers

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.

like image 143
Some programmer dude Avatar answered Oct 07 '22 16:10

Some programmer dude