繁体   English   中英

*** 检测到堆栈粉碎 *** 双数组为双循环

[英]*** stack smashing detected *** with double array in double for cycle

正如标题所说,我用我的代码检测到堆栈粉碎。 我无法理解的奇怪事情是它正确输出卫星的所有位置,然后堆叠粉碎。 当我将限制设置为 2 时,它只输出 2 个位置但不堆叠粉碎。 我曾尝试增加数组大小以查看是否有帮助,但它根本没有帮助。

这是代码:

#include <stdio.h>
int input[4][3] = {5, 4, 4, -11, -11, -3, 0, 7, 0, -13, 2, 10};
struct Moons
{
int position[2];
int velocity[2];
};

int main()
{
struct Moons moon[3];
for (int i = 0; i < 4; i++)
{
    for (int x = 0; x < 3; x++)
    {
        moon[i].position[x] = input[i][x];
    }
}
}

在 C 中声明数组时指定的数字不是最大索引,而是元素的数量。 分配足够的元素。

#include <stdio.h>
int input[4][3] = {5, 4, 4, -11, -11, -3, 0, 7, 0, -13, 2, 10};
struct Moons
{
int position[3]; /* increase this */
int velocity[2]; /* not used, but should be increased too? */
};

int main()
{
struct Moons moon[4]; /* increase this */
for (int i = 0; i < 4; i++)
{
    for (int x = 0; x < 3; x++)
    {
        moon[i].position[x] = input[i][x];
    }
}
}

请注意,访问数组越界会调用未定义的行为 即使存在越界写入,也不需要发生堆栈粉碎检测或分段错误。

C数组从索引0开始,到索引“size-1”结束。 因此,在您的代码中, moon[3]数组具有元素: moon[0]moon[1]moon[2] -但是即使i的值为3您的外部i循环也会运行-因此您正在尝试引用超出其边界的数组元素。 同样对于您的内部x循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM