Search code examples
cpointersmemoryhardcoded

Can hard-code address and manually assign it to a pointer?


When I compile this code :

int main() {

  int a = 10;
  int *p = &a;

  printf("%p",p) // or printf("%p",&a);

  return 0;
}

it prints 0022ff38. Then this code :

int a=10;
int *p =(int *)0x22ff38;

printf("%d",*p); //does not output 10;

should print 10, but it output another thing(2293560).

But when I edit the code, and add a single line :

  int main() {

  int a = 10;
  int *p =(int *)0x22ff38;
  
  printf("%p",&a);
  printf("%d",*p); // Now it prints correctly:10

  return 0;
}

Every thing is ok!.

Questions:

  1. Why my code does not output a value in first code?
  2. What is usage of this way addressing pointers? is it useful?

Edit : I have no problem in Linux, because in Linux every time that I run the code, the variable address changes and program output segmentation fault. but in windows address remains the same, and it is expected that manual addressing work in windows.


Solution

  • Compilers are smarter than you think. For example, given this code:

    int main() {
      int a=10;
      int *p =(int *)0x22ff38;
    
      printf("%d",*p);
    }
    

    The compiler is going to see that a is never even used. So it will never bother to actually allocate any memory for it.

    If you add a printf("%d", a), the compiler might only put a in a register and never in memory.

    Fundamentally, you can't assume that two programs will put variables in the same place in memory.