Array out of bounds causes a dead loop

Source: Internet
Author: User

<span style= "font-family:arial, Helvetica, Sans-serif; font-size:12px; " > #include <stdio.h></span>
int main () {    int i;    int a[5];        for (i = 0; I <= 5; i++) {        a[i] = 0;        A[i] =-I.;     The main is finally given a value smaller than 5 can be        printf ("%d  %d\n", I,a[i]);    }    return 0;}


A variable is passed in as a function parameter, but after the function call is finished , the value of the variable has changed, do not know why. It turns out that there is an address cross-border problem in the function, which causes the value of the variable to be changed, a bit incredible! For example, the following program, because the array subscript out of bounds causes a dead loop:



originally a simple array subscript out-of-bounds resulted in a dead loop, mainly due to compiler address space allocation.
in-memory addresses are assigned as follows:

High Address | i | a[4] | a[3] | a[2] | a[1] | a[0] | low address

The array address gradually increases, and the value of I is changed just beyond the bounds.
Although some compilers have optimized the memory gap between the array and I, if I cross the boundary seriously, such as accidentally giving 50, it will lead to a dead loop.


The above is in GCC (optimized), but in some gcc it is optimized. VC has been tested, but the operation will be an error in the process.



Array out of bounds causes a dead loop

Related Article

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.