我得到方形阵列的意外结果?

I get an unexpected outcome for square array?

我得到了正方形的结果

squares = [ 512, 1, 4, 9, 16, 25, 36, 49 ]

我知道我达到了极限,但 512 是从哪里来的?你能解释一下发生错误所涉及的所有步骤吗?

int main()
{
    unsigned squares[8];
    unsigned cubes[8];
    for (int i = 0; i <= 8; i++) {
        squares[i] = i * i;
        cubes[i] = i * i * i;
    }
}

您正在访问超出限制的内存

for (int i = 0; i <= 8; i++) 

应该是

for (int i = 0; i <8; i++) 

记住 unsigned squares[8]; 允许您合法 访问 squares[0] 最多 squares[7]

I know i reached the boundaries of my limit but where did 512 come from.

根据 ISO/IEC 9899:201x 6.5.10->fn109

未定义非法内存访问的后果

Two objects may be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated. If prior invalid pointer operations (such as accesses outside array bounds) produced undefined behavior, subsequent comparisons also produce undefined behavior


您可以使用调试器(例如 gdb)或检测框架(例如 valgrind)来查找值的来源。这里的 512 看起来像 8 的立方,但不能保证您在下一个 运行 上会得到相同的值。此外,程序可能会崩溃。

I know i reached the boundaries of my limit

那么你也应该知道后果。访问越界内存调用 undefined behavior.

保持在有效内存限制内。使用

for (int i = 0; i <8; i++) 

我想说的和大家说的一样。它是 undefined behavior,你不应该那样做。

现在,您会问 未定义的行为 是否是发生任何事情的原因。

我会说,是的,可能。


现在,您可能认为这是对问题的简单回答。

可能是,但是..

这类问题的主要问题是,很难重新创建相同的案例并调查究竟是什么导致了它的行为。因为 未定义的行为,嗯,行为方式非常不确定。

这就是人们不尝试回答这类问题的原因,人们建议远离未定义的行为领域。