Changing Array Values In Function - Inline Assembly

2k views Asked by At

So I taught myself x86 Assembly a while back and was just playing around with inline Assembly in C++.

So what I want to do is in a functions parameters, pass in an array, an index ( unsigned int ) and a number. With assembly it will then change the value in that memory location of the array to the passed in value. So the code looks like this.

inline void Set( int pArray[], unsigned int pIndex, int pNum ) {
    __asm {
        mov ebx, pIndex
        mov eax, 4
        mul ebx
        mov ebx, pNum

        lea edi, pArray
        mov [ edi + eax ], ebx
    }
}

int main() {
    int myArray[ 5 ] = { 1, 2, 3, 4, 5 };
    Set( myArray, 2, 7 );
    std::cout << myArray[ 2 ] << std::endl;
}

So the code should load the start of the array address, get the index and multiply it by 4 so the memory location is moved by that many bytes, and it changes it to the value passed in. However, when I do this, the value stays the same. Why is that? What is going wrong?

1

There are 1 answers

2
TheCppZoo On

lea stands for "Load effective address", your lea puts the address of the argument. What you mean is lea edi, [pArray]

However, there are two more things: 1) You don't have to multiply by four. You can do lea edi, [pArray + 4*ebx] Since the "scale index byte" addressing mode lets you multiply by 4 and add an immediate address.

2) You are assuming 32 bits. What computer are you using that in the middle of 2015 is still working in 32 bit mode?

I am rusty on intel syntax assembly. May I recommend you to learn the integration of assembler and C++ code in GCC? https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html