Incredible C++ Snippet - How it works
September 24th, 2008
I think it’s time to disclose the secret of that piece of code. First of all it’s not that tricky as you might have expected. You just have to get some basic knowledge about memory allocation.
Probably most programmers if they have a look at those few lines would say that here a beginner didn’t pay attention and that the program will poorly fail by an access violation error or something similar.
For everybody who didn’t try out this snippet himself:
If y is declared before x in the line the loop is becoming an endless loop. If it’s declared the other way round the program seems to work correctly.
First of all I have to clarify that even if we declare y before x in that line, x is first allocated in memory. It’s read by the machine from right to left.
Second thing which is important to know is that memory is always allocated from top to bottom (for our imagination).
For better explanation I changed the order of x and y:
int y,x; int feld[5];
On the stack first of all y gets it’s space of 4 bytes after that x gets the same. After that above those two the array gets 5 times 4 bytes (20 bytes).

After running the loop 5 times (from 0 up to 4) the array is filled with values. Until here everything works as it should.

But wrongly the loop is run one more time (<=5) and that's why the next value is written into the space that was allocated for x (as you can see on the picture below). In fact x gets overwritten...

The endless loop was caused by writing every time again 1 into y.
This is no black magic and it’s also not illegal according to the C++ standart. It’s just a bad error done by the programmer which often happens and usually almost not fineable in a few minutes.
It should just show you to be careful with your allocations.






Won’t this vary depending on how the stack is allocated? You are assuming the stack grows up and not down.
Comment by MAttd00d — October 12, 2008 @ 6:43 pm
as far as I know on linux and windows stack is alloceated that way…
Comment by Kai — October 12, 2008 @ 11:21 pm
That code most certainly is illegal according to the C++ Standard! Furthermore, optimisation can change the behaviour of this type of code.
Try something like (I hope this comes out OK)
#include
int main(void)
{
int x;
int y[5];
x = 0;
y[5] = 1;
std::cout << x << std::endl;
}
With no optimisation this prints 1, because y[5] does overwrite the memory of x. However, with optimisation turned on, it outputs 0, because the compiler “knows” that x = 0, and just turns the code into:
int main(void)
{ std::cout << 0 << std::endl; }
Comment by Azumanga — December 3, 2008 @ 11:32 pm