Home > Enterprise >  C's strange pointer arithmetics
C's strange pointer arithmetics

Time:08-21

I was working on pointers. I saw a code snippet but I couldn't understand how it works. The strange thing is that when the k function is executed, the expression y = 2 doesn't seem to work. Because the output is y = 1 instead of y = 2. Any idea about this?

#include<stdio.h>

void k(void){
    int x;
    *(&x 5)  = 7;
}

void main(void){
    int y = 1;
    y = 1;
    k();
    y = 2;
    printf("y = %d", y);
}

CodePudding user response:

There is undefined behavior (UB) on the *(&x 5) = 7; line. When there is UB, the program can do anyting including formatting your hard drive and outputting y=1.

To learn what is happening under the hood, you can check the assembly output.

CodePudding user response:

The function k() invokes undefined behaviour.

This is because first you declare a local variable x. After this you try to add 7 to the address &x 5 which goes past the end of x.

The strange thing is that when the k function is executed, the expression y = 2 doesn't seem to work

y is a local variable in main() so calling k() won't have any affect on it.

  • Related