堆栈损坏,不知道是什么原因造成的

Stack Corruption, have no idea what's causing it

本文关键字:是什么 损坏 不知道 堆栈      更新时间:2023-10-16

所以,为了有点事要做,我在C++中实现了AES算法。它的编译和链接非常好。不过,在我运行它的那一刻,VS2015报告称堆栈在变量"temp"周围已损坏。它向我展示了它发生的确切位置,但我在代码中看不到任何奇怪的东西:

void rotWord(Word &it)
{
    Word temp;
    for (int i = 0; i < 4; i++)
        temp[(i - 1) % 4] = it[i];
    for (int i = 0; i < 4; i++)
        it[i] = temp[i];
}

顺便说一下,Word被声明为typedef Byte Word[4],其中Byte只是一个类。知道是什么导致了这里的堆栈损坏吗?如果需要,我可以发布完整的来源。

for (int i = 0; i < 4; i++)
    temp[(i - 1) % 4] = it[i];

猜猜(0-1(%4是什么?

是-1。

在循环的第一次迭代中,i为0,这将计算为:

temp[-1]=it[0];

将其更改为:

for (int i = 0; i < 4; i++)
    temp[(i + 3) % 4] = it[i];
temp[(i - 1) % 4] = it[i];

对于i = 0

temp[((0 - 1) % 4]
temp[(-1) % 4]
temp[-1]

这是未定义的行为。