Ivan Akulov
Ivan Akulov

Reputation: 4323

Accessing element in array with assembly

Assume the following function:

void asmFunction(const int *first, ...) {
    __asm {
        xor eax, eax
        add eax, [first][0]
        ; ...
    }
}

It is being called this way:

int first[] =  { 0, 0, 0, 0, 0, 0, 0, 5, 7, 6, 2, 4, 3, 5 };
asmFunction2(first, ...);

As far as I understand, the second assembly line must add 0 element of array first to eax. However, a random value is being added. When debugging, first[0] equals 0, as it must be. What is the problem with the code?

I code in Visual Studio 2013 on 64-bit machine.

Upvotes: 3

Views: 1648

Answers (1)

Jester
Jester

Reputation: 58762

That is a strange syntax and probably doesn't do what you want. If you disassemble the generated code you will most likely see something like add eax, [ebp+8]. The random value added should be the value of first, which is a pointer. You have effectively done eax += first. To get at the elements you need a level of indirection, that is eax += *first. For example this could work:

mov edx, [first]
add eax, [edx]

Upvotes: 1

Related Questions