0

I inherited code that runs perfectly in 32-bit, but when I change the compiler to 64 bit, I get a error if I run the code. If I step the code, it (almost always) works just to fail later. There is a lot of pointers in the code, and C++ is not my strong suite. Is it possible that somebody can pick up why the error occur?

What I need to understand is: Is it fine to create the BYTE*** first, and then the BYTE**, and BYTE* is never assigned to. I don't understand how this works. I would thought that BYTE* gets assigned to first, then BYTE** and then BYTE***. Why does this work on x86, but not 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;
}
Jaques
  • 2,215
  • 1
  • 18
  • 35

1 Answers1

5

Here's your problem: AllocMemory(arg_0 * 4)

On a 32-bit system the size of pointers are 32 bits, i.e. four bytes. On a 64-bit system pointers are 64 bits, eight bytes. Use correct sizes (using the sizeof operator) and it should work fine.


For example, in the CreateBytes function you have

BYTE** hedi = (BYTE**)AllocMemory(arg_0 * 4);

Replace that with

BYTE** hedi = (BYTE**)AllocMemory(arg_0 * sizeof *hedi);

There are also many other problems, like the code allocating memory with malloc and freeing it with delete. That leads to undefined behavior.

And I wont even mention the naming of variables or lack of comments...

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621