James Leonard
James Leonard

Reputation: 3753

On dynamic nature of memory, C++ example

Consider the following snippet

int x[] = {1,2,3};
cout << *x << endl;      // 1
cout << *(x+1) << endl;  // 2
cout << *(x-10) << endl; // Different number each time i run the program

Why is it that last cout consistently display a different number each time i run the compiled program? It is understood that result is unpredictable and is undefined, but i would imagine it should be consistent. Why does it change?

Upvotes: 0

Views: 119

Answers (5)

Nymer
Nymer

Reputation: 261

Why should it be consistent? Its a pretty much random value of your computers memory. x doesn't always point to the same location and the contents of *(x-10) changes as well.

Upvotes: 3

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

This is undefined behavior. You also might have Address space layout randomization (ASLR)

Upvotes: 2

Coding Mash
Coding Mash

Reputation: 3346

The memory block you are trying to access is not legally owned by your array and the program. That portion of memory would be owned by some other process going on. so every time it holds different value. It is also possible that you get the same answer some other time.

Upvotes: 4

Dervall
Dervall

Reputation: 5744

If you understand that the result is unpredictable and undefined, then why do you also think it must be consistent? There are no guarantees for anything when reading outside of your memory. It might as well crashed the program.

Upvotes: 0

justin
justin

Reputation: 104698

as you mentioned, it is undefined behavior…

one explanation: you are reading arbitrary/random memory. who knows what it was used for before you read it?

Upvotes: 2

Related Questions