Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a number value using an inline assembly in C++

I'm trying to increase a number value by using an inline assembly in C++. The reason that I do it that way is to practice my "inline assembly" skills.

Well that's what I've done so far:

void main()
{
    int x;
    cout << "Please enter a number ";
    cin >> x;
    cout << "The number you entered is: " << x << "\n";
    foo(&x);
    cout << "The new number is: " << x;
    cin >> x;
}

void foo(int *x) 
{
    __asm
    {
        inc [x]
    };
}

And the value never changed.

like image 982
Imri Persiado Avatar asked Oct 05 '22 18:10

Imri Persiado


1 Answers

You are incrementing the value of x, actually. X in terms of assembly language is a constant containing the address of x variable (of function foo). Which, in turn, contains the address of main's x. So, inc [x] causes an increment of the pointer. You need to increment the value stored at the address [x], like inc [[x]]. Of course you can not do it in one instruction in assembly language since you need two memory accesses: to know where the value is stored and to actually increment the value. So I'd advise a code like this:

push eax
mov eax, [x]
inc dword ptr [eax]
pop eax
like image 74
Aneri Avatar answered Oct 10 '22 01:10

Aneri