void foo() {
int value = 0;
char buf[4];
buf[4] = 1;
printf("value: %d\n", value);
}
int main() {
foo();
return 0;
}
Why does 'value' print 1?
I believe this has to do with buffer overflow and little endian but I am finding it hard to grasp.
Because it is Undefined Behaviour.
It is enough to change the optimization options and you will get different results.
Godbolt for example:
But it does not have to be like this. It can end up in the segfault or something else may happen.
https://godbolt.org/z/TEbWbMvsa
You cant know it. Order is not specified.
valuecan be optimized out and not stored on the stack at all. You need to know your ABI and compiler very well to predict it.In your case: