Introduction: Today, the class teacher gave me a question about the cross-border C language array. Although it is not difficult, it involves the knowledge of memory allocation and array out-of-bounds, I thought it was impossible to run it .. I came back and tried it. I also encountered some problems. Here is a summary ~ PS: Use codeblocks wood to find the amount of memory to view... Only printf is available... Code:
# Include <stdio. h> main () {int V1; int A [3]; int V2; int I; V1 = 10; v2 = 20; printf ("V1 ADDR = % x, array ADDR = % x, V2 ADDR = % x, I addr = % x \ n ", & V1, A, & V2, & I ); printf ("V1 = % d, V2 = % d \ n", V1, V2); for (I =-1; I <= 3; I ++) {A [I] = I * 2;} printf ("V1 = % d, V2 = % d \ n", V1, V2); Return 0 ;}
The variables are stored in the stack according to the declared order, which may vary depending on the CPU. My CPU is an Intel I5 processor, and the bottom of the stack is a high address, so the storage is as follows:
Result: If you change the Declaration Order, the memory distribution will naturally be different, because the order of pushing to the stack has changed, which may cause unexpected consequences, such:
Int V1; int V2; int A [3]; int I;
The memory distribution is as follows: the program running result will not run until it enters the endless loop. The reason is that when it enters the for loop, the Statement A [I] = I * 2; the I (a [-1]) value is modified, and the loop ends with I ++, that is,-2 plus 1 Programming-1, I =-1 continues the endless loop, the example I wrote with me is quite clever ~