gpt4 book ai didi

c - 为什么这个 for 循环在某些平台上退出,而在其他平台上不退出?

转载 作者:太空狗 更新时间:2023-10-29 16:13:43 24 4
gpt4 key购买 nike

我最近开始学习C,正在上以C为主题的类(class)。我目前正在玩循环,我遇到了一些我不知道如何解释的奇怪行为。

#include <stdio.h>

int main()
{
int array[10],i;

for (i = 0; i <=10 ; i++)
{
array[i]=0; /*code should never terminate*/
printf("test \n");

}
printf("%d \n", sizeof(array)/sizeof(int));
return 0;
}

在我运行 Ubuntu 14.04 的笔记本电脑上,这段代码没有中断。它运行到完成。在我学校运行 CentOS 6.6 的计算机上,它也运行良好。在 Windows 8.1 上,循环永远不会终止。

更奇怪的是,当我编辑 for 的条件时循环到:i <= 11 ,代码仅在运行 Ubuntu 的笔记本电脑上终止。它在 CentOS 和 Windows 中永远不会终止。

谁能解释内存中发生了什么,以及为什么运行相同代码的不同操作系统会产生不同的结果?

编辑:我知道 for 循环超出范围。我是故意的我只是无法弄清楚不同操作系统和计算机之间的行为有何不同。

最佳答案

On my laptop running Ubuntu 14.04, this code does not break it runs to completion. On my school's computer running CentOS 6.6, it also runs fine. On Windows 8.1, the loop never terminates.

What is more strange is when I edit the conditional of the for loop to: i <= 11, the code only terminates on my laptop running Ubuntu. CentOS and Windows never terminates.

您刚刚发现内存踩踏。您可以在这里阅读更多相关信息:What is a “memory stomp”?

当你分配 int array[10],i; 时,这些变量进入内存(具体来说,它们分配在堆栈上,这是与函数关联的内存块)。 array[]i可能在内存中彼此相邻。似乎在 Windows 8.1 上,i位于array[10] .在 CentOS 上,i位于array[11] .在 Ubuntu 上,它不在任何位置(也许它在 array[-1] ?)。

尝试将这些调试语句添加到您的代码中。您应该注意到在第 10 或 11 次迭代中,array[i]指向 i .

#include <stdio.h>

int main()
{
int array[10],i;

printf ("array: %p, &i: %p\n", array, &i);
printf ("i is offset %d from array\n", &i - array);

for (i = 0; i <=11 ; i++)
{
printf ("%d: Writing 0 to address %p\n", i, &array[i]);
array[i]=0; /*code should never terminate*/
}
return 0;
}

关于c - 为什么这个 for 循环在某些平台上退出,而在其他平台上不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31016660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com