Originally Posted by
Fergal
Code:
int myArray[3] = {0};
myArray[111] = 22;
printf("\n%d\n", myArray[111]);
The code above is not giving any errors or warnings when I compile and run it in CodeBlocks 20.03.
The code echos the value of "22" to the command line.
Should I be concerned that running code like this could overwrite memory it shouldn't?
Do you know why this code is not presenting any errors or warning?
Thanks
Yes, you should get an error if you use "-fsanitize=address -O2 -Wall" with GCC. However, keep in mind that the compiler cannot check for values that contain non constant/literal values. This is why it will always be your responsibility to check if a value is out of index. For that reason, always keep track of the length of the array in a variable.
Another way you could get it is by dividing the total size of the array with the size of an element. For example your array stores integers (4 bytes). They are 3 of them so the size is 4*3 = 12 bytes for the whole array. So to get its length, you divide that by the value of an element and you get 3 (12 / 4 = 3)! In case you still don't understand or I'm not a good teacher, here is the code:
Code:
int myArray[3] = {0};
printf("The length of my array is (%lu)\n", sizeof(myArray) / sizeof(myArray[0] ));