数组越界出现死循环问题

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int i = 0;
 6     int arr[3] = {0};
 7     for(; i<=3; i++){
 8         arr[i] = 0;
 9         printf("hello world\n");
10     }
11     return 0;
12 }

运行代码是会陷入输出hello world的死循环。

原因是数组越界,a[3]的地址指向了变量i的地址。

这让我疑惑,为什么a[3]的地址指向变量i的地址?

 经过大佬的解释

 才理解。

因为会进行8字节对齐,i的地址就会紧跟数组后面,当i=3时,数组地址产生偏移即a[3]_address = base_address + 3 * type_size=i_address。然后i=0,就陷入了死循环中。

对于8字节对齐,同样

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int j=3;
 6     int i=0;
 7     int arr[3] = {0};
 8     for(; i<=3; i++){
 9         arr[i] = 0;
10         printf("%d\n",i);
11         printf("hello world\n");
12     }
13     printf("%d%d\n",j,i);
14     return 0;
15 }

#include <stdio.h>

int main()
{
    int i = 0;
    int j=3;
    int arr[2] = {0};
    for(; i<=3; i++){
        arr[i] = 0;
        printf("%d%d\n",j,i);
        printf("hello world\n");
    }
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/foodiedragon/p/11973469.html