Pointer to an unspecified variable [duplicate]
The following code gets compiled
int v[] = { 0,1,2,3,4,5,6,7,8,9 };
std::cout << v[10] << std::endl;
int x;
int* ptr = &x;
std::cout << *ptr << std::endl;
I would like to understand why it was possible to display v[10] and *ptr and also why v[10] and *ptr have the same value. Could you please provide an explanation?
It is undefined behavior but for some of compilers it is how the variables are places in memory. In C/C++ you have direct access to memory (as a huge space with some addressation). x
is just placed just after v[]
.
v[10]
means 10th object from start (v is pointing to beginning). If it exceeds the size of container, it will try to decode what is stored at this address. In your case, there is stored variable x
This undefined behavior is very often used to make attacks called "BufferOverflow" so you can search for it and see how it can be used to alter behavior of some applications :)
There is no array element v[10]
. You are accessing the array out of bounds. This is undefined behavior, which means that anything can happen.
What is probably happening on your computer is that the compiler is storing x
immediately after v
in memory, so when you read from v
out of bounds, you are actually reading x
.
However, if you run this program on a different compiler, the compiler may decide to not store x
immediately after v
in memory, and the behavior of the program may be different. It may crash, or something completely different may happen. You can never rely on a specific behavior, when invoking undefined behavior.
I would like to understand why it was possible to display v[10] and *ptr
It is in the capabilities of your computer to display some output.
The behaviour that you observe is not guaranteed because the behaviour of the program is undefined.
why v[10] and *ptr have the same value
Why shouldn't they, considering that you haven't taken any steps to ensure that they don't have the same value?
The behaviour of the program is undefined, so it may seem like they have the same value just as well as it may seem like they don't have the same value, just as well as the program may crash.