为什么在C中发生数组越界时我的程序为什么没有进入无限循环 [英] Why does not my program go into infinite loop when array out of bounds occur in C

查看:75
本文介绍了为什么在C中发生数组越界时我的程序为什么没有进入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(){
   int i;
   int arr[4];
   for(int i=0; i<=4; i++){
      arr[i] = 0;
   }
   return 0;
}

  1. 我在YouTube上的CS107(第13讲)上观看了一个视频,其中显示了此示例,并通过显示内存图告诉了上述程序为什么会导致无限循环. arr [4]超出范围,应该导致存储i的地址,并将i的值改回0,从而导致无限循环.但是,当我尝试使用gcc编译器在Mac上运行此程序时,执行了5次循环(通过插入printf进行检查).即i = 0、1、2、3、4的值.

推荐答案

当存在未定义的行为时,您不能指望单个或特定行为.什么都可能发生.
该视频中所说的只是不确定行为的许多可能性中的一种,而您得到的是另一种可能性.一个人不应该依赖任何特定的行为.

When there is undefined behavior you can't expect a single or particular behavior. Anything could happen.
What said in that video is just one of many possibilities of undefined behavior and what you are getting is another possibility. One should not rely upon any particular behavior.

这篇关于为什么在C中发生数组越界时我的程序为什么没有进入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆