7
int i=10;
printf("Address of i = %u",&i);

Output:
Address if i = 3220204848

Output on re-execution:
Address of i = 3216532594

I get a new address of i each time I execute the program. What does this signify?

Mitch Dempsey
  • 38,725
  • 6
  • 68
  • 74
Mohit
  • 539
  • 3
  • 9
  • 16
  • You're producing undefined behaviour. Don't use %u to print a pointer, use `printf("%p", (void*)&i);` – Secure May 17 '10 at 05:51
  • (this does not happen in the debugger gdb, see [c - Why does the address of a local variable vary when executing multiple times, but not when debugging it with GDB? - Stack Overflow](https://stackoverflow.com/questions/7720462/why-does-the-address-of-a-local-variable-vary-when-executing-multiple-times-but?rq=1)) – user202729 Dec 19 '21 at 03:08

4 Answers4

10

It signifies that your program is being loaded a different (virtual) address each time you run it. This is a feature called Address Space Layout Randomization (ASLR) and is a feature of most modern operating systems.

Dean Harding
  • 71,468
  • 13
  • 145
  • 180
1

That's how operating systems work. When you declare a variable, you're asking the underlying systems to allocate a memory block (address) to store that data (or a pointer to another block if you're dealing with pointers, but here you've got a primitive, so it's just data being stored). The program doesn't care where the memory is, just that it exists, because it knows how to keep track of whatever it's given.

As the programmer, this really isn't that big of a deal unless you're doing some incredibly low-level work. The hardest part of this to really grasp, for most people, is that when you work with pointers, you can't equate things the same way you can primitives, because pointers consider their values (when using == as an equator) to be their memory addresses.

Jason B
  • 667
  • 1
  • 9
  • 16
1

Disable ASLR using:

echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

You will always see the same address.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

At the time of c program execution another processes are running.While executing a code again you will allocate new address previously allocated address will be allocate for another process.