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
I understand it's undefined behavior. I was just wondering how this is related to little endian. When I went past buf[3] into buf[4], it started changing the next byte in memory. How do I know the next byte in memory is 'value'?
You cant know it. Order is not specified. value
can 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:
+ 0x07: value byte 4 MSB
+ 0x06: value byte 3
+ 0x05: value byte 2
+ 0x04: value byte 1 LSB
+ 0x03: buf[3]
+ 0x02: buf[2]
+ 0x01: buf[1]
+ 0x00: buf[0]