0
Have a doubt in arrays
I just started learning C++ and during one of the lessons i tried to use an element of an array which didnt exist i.e i called an inexistent index. Surprisingly in the output it gave me a random 6-7 digit numerical value? Why did it do so?
1 Answer
+ 1
Welcome to the crazy world of C/C++ - where performance is in most cases the only criteria that matters!
You have just stumbled across a very typical error/risk of C/C++ - the lack of array bounds checking. This has even been used as a security exploit (see https://arstechnica.com/security/2015/08/how-security-flaws-work-the-buffer-overflow/)
Consider this code:
const int SIZE = 4;
int z, arr[SIZE] = {1,2,3,4};
for(int i = 0; i < SIZE; i++)
z = arr[i];
z will each time be assigned the next value in the array. This works fine since we are using SIZE for both the size of the array as well as the bound on the loop (even better would be to use sizeof(..). But if you change the loop to this:
for(int i = 0; i < 1000000; i++)
z = arr[i];
The compiler will still happily compile it and, when you run it, simply continue in memory, overrunning the end of the array and keeping on returning the next 4 bytes in RAM as the next value of arr!
That is also incidentally what you saw: the value returned by the program just happen to be what was in RAM at that "offset" from the start of the array.
The reason for this is that C/C++ handles arrays as pointers - see https://www.sololearn.com/Discuss/200497/why-the-array-identifier-represents-the-base-address-of-an-array for more details.