当前位置:网站首页>C trap - infinite loop problem caused by array out of bounds
C trap - infinite loop problem caused by array out of bounds
2022-08-07 05:50:00 【The calf is turning over】
一、引入
下面的程序在VSWhat can go wrong with the compiler?运行结果是什么?为什么?
#include <stdio.h>
int main()
{
int i = 0;
int arr[] = {
1,2,3,4,5,6,7,8,9,10};
for(i=0; i<=12; i++)
{
arr[i] = 0;
printf("hello\n");
}
return 0;
}
运行结果:
如下图:代码死循环

二、代码缺陷
上述代码有两个问题:
- 数组访问越界
- 死循环
三、为什么会死循环?
1、i和arr都是局部变量,Local variables in memory are stored in the stack area.
2、数组随着下标的增长,地址是由低到高变化的.
3、The memory specification of the stack area:先使用高地址处的空间,再使用低地址处的空间.
根据上述代码可知,The program will first create a variable at a high address in the stack areai开辟空间,Then in the stack area, from high to low, it is an arrayarr开辟空间
如下图
By debugging we can observe the following changes in memory:
for循环中,i 的内容是从0,一直增加到12,而数组只有
10个空间,因此会越界,每次访问arr数组i号位置时,都会将该位置内容设置为0,当访问到arr[12]时,也会将该位置内容设置为0,而位置恰好为i的位置,即arr[12]恰巧将i设置为0,因此造成死循环.

四、补充说明
The above code has different effects in different compilers,And it is related to the operating environment.
- 在VS2013/2019/2022的x86环境中,i和arrtwo integers apart.即
i<=12就死循环- 在gccThe space in the middle is separated by an integer.即
i<=11就死循环- 在VC6.0There is no extra space in between.即
i<=10就死循环
五、总结
We may encounter various problems when writing code:语法错误、编译错误、运行错误……
But we are makingBugAt the same time, try to be one Bug终结者.
学会发现问题,Solving problems and avoiding them are fundamental qualities of a qualified programmer.This requires us to master certain debugging skills,养成良好的编程习惯.
边栏推荐
猜你喜欢
随机推荐
mysql获取当前时间
实现codemirror的自定义提示的功能
数组扁平化
查找一个复杂对象或数组里面是否包含某一个值
leetcode 22 (生成括号) js 实现
lottie-web,lottie动画使用详解
机器学习之信用卡欺诈识别(严重类失衡数据建模)
Properties格式文件的读取和写入
Unity Shader: Blend混合
网络安全学习:系统基础命令操作
R语言之朴素贝叶斯方法实现对垃圾邮件的分类
jwt 认证机制
归并排序模板
mysql如何让自增id从1开始设置方法(三种方法)
支付宝支付
对于端口的粗浅理解
#region 与 #endregion 用法(注释代码的折叠)
STL-sort学习
【继承 、父类引用: super|| 权限修饰符:private、protected、默认、public || 状态修饰符:static、final】
MyTinySTL的vector源码分析









