Home > OS >  When a pointer is already linked to a variable, what happened when we change the variable address
When a pointer is already linked to a variable, what happened when we change the variable address

Time:02-19

I have just learned about pointer in c and my teacher wanted me to explain this code result:

#include <stdio.h>
int main()
{ 
    int n2= 10;
    int n1= 6;
    int n0= 5;
    printf("n2=%d, n1=%d, n0=%d\n", n2, n1, n0);
    int* p = &n1;
    *p=9;
    p  ;
    *p=15;
    p--;
    p--;
    *p=-3;
    printf("n2=%d, n1=%d, n0=%d\n", n2, n1, n0);
    getchar();
    return 0;
}

It really makes me confused by printing out only 1 line and the cmd say it returns value 3221225477. Can sb help me pls

CodePudding user response:

Unfortunately, the intention of teacher was to show the working of stack.

I believe, the teacher took the idea that, the variables are placed sequentially in the stack frame. If that is the case, then you will get output like this (output from my laptop)

n2=10, n1=6, n0=5
n2=15, n1=9, n0=-3 

Your program worked in my laptop which has gcc 4.2 and caused segmentation fault in other machines (later gcc).

But this is an undefined behaviour as Weather Vane pointed out in comments but I think this is the answer teacher wants to show (probably working of stack, incrementing and decrementing pointers to go above and below addresses).

Assuming (this is wrong thing to do), the compiler places it sequentially, then the variables can be accessed in stack similarly as arrays using pointers. But this is indeed an access violation. If you generate the assembly code for your program (gcc -S file_name.c), you can see this. In the machine where the program worked, the assembly code looked like this

movl    $10, -8(%rbp)
movl    $6, -12(%rbp)
movl    $5, -16(%rbp)

In the machine, it caused segmentation fault, it looked like this,

movl    $10, -4(%rbp)
movl    $6, -20(%rbp)
movl    $5, -8(%rbp)

rbp is the base pointer, which points to the base of the current stack frame.

  •  Tags:  
  • c
  • Related