C array setting of array element value beyond size of array

后端 未结 3 409
孤独总比滥情好
孤独总比滥情好 2020-12-19 18:43

I Have this C code snippet

int numbers[4]={1};

numbers[0]=1; numbers[1]=2; numbers[3]=3; numbers[10]=4;
printf(\"numbers: %d %d %d %d %d %d\\n\",numbers[0],         


        
相关标签:
3条回答
  • 2020-12-19 19:24
    1. This won't give an error, your array is declared on the stack so what number[10] does is write at the adress number + (10*sizeof int) and overwrites anything that would be there.
    2. As Xymostech said 0 can be as much garbage as 963180397. Printing numbers[6] will print what is stored at the address numbers + (6*sizeof int) so it depends on how your program is compiled, if you have declared local variables before of after numbers, etc.
    3. See answer 1.

    What you can do is this :

    int empty[100];
    int numbers[4]={1};
    int empty2[100];
    
    memset(empty, 0xCC, sizeof empty);
    memset(empty2, 0xDD, sizeof empty2);
    
    numbers[0]=1;numbers[1]=2;numbers[3]=3;numbers[10]=4;
    printf("numbers: %d %d %d %d %d %d\n",numbers[0],numbers[1],numbers[3],numbers[6],numbers[10],  numbers[5]) ;
    

    Now you can understand what you are overwriting when accessing out of your numbers array

    0 讨论(0)
  • 2020-12-19 19:24

    To answer your questions:

    1. Not necessarily. The compiler could reserve memory in larger chunks if you declared the array statically or you could have just overwritten whatever else comes after the array on the stack.
    2. That depends on the compiler and falls under "undefined behaviour".
    3. You set (numbers + 10) to the value after the equal sign.
    0 讨论(0)
  • 2020-12-19 19:26

    It doesn't cause any errors because it is decayed to a pointer arithmetic.

    When you write numbers[10], it is just numbers + 10 * sizeof(numbers), which is fairly correct.

    It's undefined behavior to access memory you're not meant to (not allocated for you), so every index out of bound that you access is garbage, including 0.

    Accessing indexes greater than 4 will not increase the array's size, as you said, and additionally, it does not do anything either.

    0 讨论(0)
提交回复
热议问题