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

DDe*_*ler 1 c++ corruption

因此,为了有一点事可做,我致力于用 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];
}
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*hik 5

for (int i = 0; i < 4; i++)
    temp[(i - 1) % 4] = it[i];
Run Code Online (Sandbox Code Playgroud)

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

是-1。

在循环的第一次迭代中,如果i值为 0,则计算结果为:

temp[-1]=it[0];
Run Code Online (Sandbox Code Playgroud)

将其更改为:

for (int i = 0; i < 4; i++)
    temp[(i + 3) % 4] = it[i];
Run Code Online (Sandbox Code Playgroud)