Demonstration Program of C language array out-of-bounds

Source: Internet
Author: User
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 ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.