-3

I was making practises on the logic of arrays in c and my thought on the array length declaration was unformattable if you declare an array length to be 10 integers, that array could not keep 20 integers in memory but when I tested it I saw that I was completely wrong

int main(){
    int i;
    int arr[10];
    for (i = 0;i<20;i++){
        arr[i] = i;
    }
    for (i = 0;i<20;i++){
        printf("%d \n",arr[i]);
    }


}

I was expecting to see 10 printed numbers but it prints out 20 could someone explain how is it possible?

TylerH
  • 20,799
  • 66
  • 75
  • 101
emirhan422
  • 87
  • 5
  • 1
    It just calculates the address of the 20th int following the base and attempts to print that..whether it is a valid array alement or not. (Or it causes other undefined behavior, such as aborting your program). – Paul Ogilvie Aug 07 '19 at 11:57
  • 1
    What would you expect? It does nothing other than calculating the address. It is up to you not to pass the end of the array. – Paul Ogilvie Aug 07 '19 at 11:58
  • 1
    No, you are completely right. Neither C nor C++ checks whether you access array elements beyond of size. It's just [UB](https://stackoverflow.com/a/4105123/1505939). If you are lucky your application crashs. Otherwise, you might get to your wrong conclusion... ;-) – Scheff's Cat Aug 07 '19 at 11:58
  • You were not "completely wrong", not at all. You might have been a *little* bit wrong, if your expectation was that you'd get a clear error message when you went beyond the bounds of the array. Think of it like this: "I thought you couldn't go through the intersection when the light was red. But every night for the past week I've been doing it (at 2am), and nothing bad has happened. I guess I was completely wrong." – Steve Summit Aug 07 '19 at 15:01
  • 1
    Please do not vandalize your posts by wiping the contents. Once posted, your content was immediately licensed for use under CC by-SA 4.0 (w/ attribution required). – TylerH Nov 26 '19 at 20:11

1 Answers1

3

C and C++ don't have explicit bounds checking on array sizes. When you read/write past the end of an array, you invoke undefined behavior.

With undefined behavior, your program may crash, it may output strange results, or (as in your case) it could appear to work properly. Also, making a seemingly unrelated change such as adding an unused local variable or adding a printf for debugging can change how UB manifests itself.

Just because a program may crash doesn't mean it will.

dbush
  • 205,898
  • 23
  • 218
  • 273