【发布时间】:2018-05-07 13:06:34
【问题描述】:
我继承了在 32 位下完美运行的代码,但是当我将编译器更改为 64 位时,如果我运行该代码会出现错误。如果我单步执行代码,它(几乎总是)会在以后失败。代码中有很多指针,C++ 不是我的强项。是否有可能有人可以了解错误发生的原因?
我需要了解的是:可以先创建BYTE***,然后再创建BYTE**, 和 BYTE* 从未分配给。我不明白这是如何工作的。我认为首先分配 BYTE*,然后是 BYTE**,然后是 BYTE***。为什么这适用于 x86 而不是 x64?
void* AllocMemory(SIZE_T dwBYTEs)
{
void* result;
if (dwBYTEs > 0)
{
result = malloc(dwBYTEs);
if (result != NULL)
return result;
}
return 0;
}
BYTE** CreateBytes(int arg_0, int arg_4, int arg_8)
{
BYTE** hedi = (BYTE**)AllocMemory(arg_0 * 4);
if (!hedi)return 0;
hedi[0] = (BYTE*)AllocMemory(arg_0 * arg_8 * arg_4);
if (!hedi[0]) {
delete(hedi);
return 0;
}
for (int i = arg_0 - 1; i > 0; i--) {
hedi[arg_0 - 1 - i + 1] = &hedi[0][arg_4 * arg_8 * (arg_0 - 1 - i + 1)];
}
return hedi;
}
BYTE*** CreateItem(int arg_0, int arg_4, int arg_8)
{
BYTE*** hebp = (BYTE***)AllocMemory(arg_8 * 4);
hebp[0] = (BYTE**)CreateBytes(arg_0, arg_4 * arg_8, 1);
if (!hebp[0])
{
delete(hebp);
return 0;
}
for (int i = 1; i < arg_8; i++) {
hebp[i] = (BYTE**)AllocMemory(arg_0 * 4);
if (hebp[i]) {
for (int j = 0; j < arg_0; j++) {//eax
hebp[i][j] = &hebp[0][j][i];
}
}
else {
for (int j = i - 1; j > 0; j--) {//esi
delete(hebp[j - i]);
}
delete(hebp[0]);
delete(hebp);
return 0;
}
}
return hebp;
}
【问题讨论】:
-
BYTE***OMG. -
告诉我
-
此外,此代码具有未定义的行为,因为它使用
malloc和delete而不是new:stackoverflow.com/questions/10854210/… -
@Jaques 对于它的价值
delete永远不应在malloced 内存上调用。此代码具有未定义的行为。 -
谢谢。我现在已经纠正了内存问题。下面的答案整理出来。
标签: c++ memory-management malloc