I'm trying to create a little example of 'How to use asm block in C code'. In my example, i'm trying to increment a value of variable which I created in my C code.
This is my code:
int main()
{
unsigned int i = 0;
unsigned int *ptr1;
// Get the address of the variable i.
ptr1 = &i;
// Show ECHO message.
printf_s("Value before '_asm' block:");
printf_s("\ni = %d (Address = ptr1: %d)\n\n", i, ptr1);
_asm {
// Copy the value of i from the memory.
mov bx, word ptr [ptr1]
// Increment the value of i.
inc bx
// Update the new value of i in memory.
mov word ptr [ptr1], bx
}
// Show ECHO message.
printf_s("Value after '_asm' block:");
printf_s("\ni = %d (Address = ptr1: %d)\n\n", i, ptr1);
// Force the console to stay open.
getchar();
return 0;
}
This is the result of the code in the console:
Values before '_asm' block: i = 0 (Address = ptr1: 1441144)
Values after '_asm' block: i = 0 (Address = ptr1: 1441145)
This is very wierd. I only want to update the value of the 'i' variable, but it doesn't work. In addition, the pointer 'ptr1' now points to the next memory block...
Why is this happening ? And how should I solve this problem?
EDIT:
Thanks to the comments below, I solved the problem. The main change is in this line:
// Increment the value of i.
inc bx
Due to the fact that we want to increment the VALUE of the variable 'i', we should use brackets. In addition, the bx register should be changed now to 'ebx', that is a 32-bit register. Because of using the 'ebx' register, the expression 'word ptr' should be replaced with 'dword ptr'.
The code of the asm block, after the editings:
_asm {
// Copy the value of i from the memory.
mov ebx, dword ptr [ptr1]
// Increment the value of i.
inc [ebx]
// Update the new value of i in memory.
mov dword ptr [ptr1], ebx
}