-1

I am getting a different memory location in my C program every time I run the exact same statement. Shouldn't this never change? And yes it still happens if I change &p to &x. I realize those two should be different but this happens when I repeatedly run (NOT COMPILE) the program to view it's memory address.

#include <stdio.h>
#include <string.h>


int main()
{
  int x = 30;
  int* p;
  p = &x;
  
  printf("%p \n", &p);
}

Proof

Nicky Reds
  • 33
  • 6
  • 3
    Why do you think that it *should never change*? – alex01011 Dec 28 '21 at 03:01
  • Fyi, given that `printf` argument list, both the `int x` declaration and `p = ` statement are pointless; you're printing the address of the pointer variable `p`, not the address held *within* the pointer variable `p`. And you really should include the repetitious sample output you claim you're getting. – WhozCraig Dec 28 '21 at 03:03
  • @alex01011 I was taught that the memory address you designate for a variable would never change. How else can the computer use a pointer? – Nicky Reds Dec 28 '21 at 03:07
  • whozcraig, Yes I'm doing that intenionally to check to see if the address held for p as a pointer changes. It does. Also you have to click proof to see the image I included of the repitition. – Nicky Reds Dec 28 '21 at 03:09
  • 011c Thank you, that is exactly what I was looking for. – Nicky Reds Dec 28 '21 at 03:13

1 Answers1

2

Why does the memory address change every time I run

Because your system uses address space layout randomization (ASLR), and in particular randomizes stack placement.

On Linux, you could disable ASLR for a single process like so:

setarch -R ./a.out

Running the program under GDB also disables ASLR by default.

I was taught that the memory address you designate for a variable would never change.

The address of a stack variable will in fact never change during a particular execution of your program. It can only change between different runs.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362