堆栈损坏,不知道是什么原因造成的
Stack Corruption, have no idea what's causing it
所以,为了有一点事可做,我致力于用 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
只是一个 class。知道是什么导致这里的堆栈损坏吗?如果需要,我可以 post 完整的源代码。
temp[(i - 1) % 4] = it[i];
对于i = 0
temp[((0 - 1) % 4]
temp[(-1) % 4]
temp[-1]
这是未定义的行为。
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];
所以,为了有一点事可做,我致力于用 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
只是一个 class。知道是什么导致这里的堆栈损坏吗?如果需要,我可以 post 完整的源代码。
temp[(i - 1) % 4] = it[i];
对于i = 0
temp[((0 - 1) % 4]
temp[(-1) % 4]
temp[-1]
这是未定义的行为。
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];