+ 1
Can someone please explain what happens when this code runs and makes it to print random values because I don't understand it.
3 Antworten
+ 1
It's an error. Out of range. Your array have only 8 elements, but you try to take 9'th. The last index of this array is 7 (because index start from 0)
+ 2
Lets say your computer has 25 bytes of memory, and lets say the memory contains these values right now:
23, 73, 50, 87, 72, 93, 97, 65, 51, 89, 32, 16, 47, 36, 43, 96, 46, 71, 17, 59, 70, 33, 98, 88, 2
Now your program starts running and asks for an array that is 8 bytes long. ( I know an int is not a byte, but lets pretend it is )
The OS for some reason puts the array at on offset of 5 bytes and initializes it with 1, 2, 9, 4, 5, 6, 7, 8.
Therefore the memory now contains:
23, 73, 50, 87, 72, 1, 2, 9, 4, 5, 6, 7, 8, 36, 43, 96, 46, 71, 17, 59, 70, 33, 98, 88, 2
Now we tell the program to give us the 9th element in the array, the program happily does it without arguing and goes:
"Ok, the array is at the 5th index, if I want the 9th element I have to add those 2 numbers together so I have to access the 14th index."
So it goes out and grabs the number at the 14th index which contains the number 43.
It's not part of the actual array, but you can still read ( and write ) outside of it.
Memory is basically 1 huge array and your array is inside that.
Accessing an array at an index that is bigger than the actual array is called an out-of-bounds access and this is undefined behavior.
Anything could happen.
The memory at that index could be part of something else in your program, it could be from another program that used that address space before, it could just be 'random' data that was there on startup.
Your OS could shutdown your program ( usually happens if the index gets too big or too small ) or virus scanners can be more likely to flag your program.
Back in the old days you could even overwrite part of the kernel or BIOS.
Basically, try not to do it :)
0
Like I said, it's undefined behavior, anything could happen.