1

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?

user438383
  • 5,716
  • 8
  • 28
  • 43
A413
  • 121
  • 5

4 Answers4

3

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 :)

Karol T.
  • 543
  • 2
  • 13
2

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.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

In simple words, that's just a coincidence. This is a very simple program. That behavior is very unlikely to happen in big and complex programs. It is undefined behavior and you better avoid doing those sorts of things.

why v[10] and *ptr have the same value.

A possible cause might be that v[10] is dereferencing the address of x which is declared right after the v array.

digito_evo
  • 3,216
  • 2
  • 14
  • 42