Search code examples
stringassemblyreplacecharactermasm

Replace a character in a string using assembly code in MASM


So my program is very simple. I have a string "Hello World" and I want to replace 'H' with 'A'. So here is my assembly code for MASM.

char* name = "Hello World";
_asm
{
mov eax, name;
mov ebx, 'A';
mov [eax], ebx;
}

printf("%s", name);

Visual Studio cannot compile this. It alerts me that this program is not working. I suspect my syntax for mov[eax], ebx might be wrong. All comments are appreciated. Thanks!

Here is the image of the alert: https://www.dropbox.com/s/e5ok96pj0mxi6sa/test%20program%20not%20working.PNG


Solution

  • "Hello World" is a literal, i.e a non-writeable constant string. 'name' is a pointer which points to that literal. You can instead define an array, which has to be populated with that literal, i.e. the literal is copied into the array:

    #include <stdio.h>
    
    int main (void)
    {
        char name[] = "Hello World";
        _asm
        {
            lea eax, name;    // EAX = address of name
            mov ebx, 'A';
            mov [eax], bl;
        }
    
        printf("%s", name);
    
        return 0;
    }
    

    The original code works, if you use the C89-Compiler of MSVC (file-extension .c or command line option /TC), but that does not really meet the standard.