int main(void)
{
int *x = 0;
int y = 0;
x = &y
*x = 1
*(x+1) = 10
return 0;
}
When I perform *(x+1) = 10
and try to print out the address of x, it points to 0x7fff0000000a
and get this when I try to print out the value of x Cannot access memory at address 0x7fff0000000a
Before *(x+1) = 10
, the address of x comes out to (int *) 0x7fffffffe4d4
and the value of x comes out to 1
The question I have is, what exactly is *(x+1) = 10
doing? The address of x and y are 4 bytes apart. Since x points to y, and x was added 1, it should point back to x itself
Address of x: (int **) 0x7fffffffe4d8
Address of y: (int *) 0x7fffffffe4d4
what exactly is
*(x+1) = 10
doing?
It re-interprets x
as a pointer to the initial element of an array, and tries to access that "array"'s second member (i.e. an item at index 1
). Since x
is neither an array nor a pointer into an array, the assignment is undefined behavior.
The address of
x
andy
are4
bytes apart.
This happens to be the case with your compiler. It may be different on other systems, depending on many factors, such as the compiler, the optimization flags, the size of a pointer, the size of an int
, and so on. The important thing is that no matter where x+1
points, it is illegal to dereference it, because x
points to a scalar local variable.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments