Replace a character in a string using assembly code in MASM

10,582

Solution 1

"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.

Solution 2

First Character

    mov eax, _name;    // EAX = address of name
    mov bl, 'A';
    mov byte[eax], bl;

Second Character

mov eax, _name;    // EAX = address of name
mov bl, 'A';
mov byte[eax+1], bl;

MOVS

MOVS - This instruction moves 1 Byte, Word or Doubleword of data from memory location to another.

LODS

LODS - This instruction loads from memory. If the operand is of one byte, it is loaded into the AL register, if the operand is one word, it is loaded into the AX register and a doubleword is loaded into the EAX register.

STOS

STOS - This instruction stores data from register (AL, AX, or EAX) to memory.

CMPS

CMPS - This instruction compares two data items in memory. Data could be of a byte size, word or doubleword.

SCAS

SCAS - This instruction compares the contents of a register (AL, AX or EAX) with the contents of an item in memory.

Share:
10,582
Phuc
Author by

Phuc

Updated on June 04, 2022

Comments

  • Phuc
    Phuc almost 2 years

    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

  • Phuc
    Phuc almost 10 years
    So I changed char* to char []. The code works fine. And you're right. I can't change the literal. So another way I'm thinking is to work around char*. I create a char* name, copy the string to a char name2[], change a character in there. And then let name points to the new name2. It works. :D
  • Phuc
    Phuc almost 10 years
    oh but I have a new problem. I printf("%s", name) only prints out "A"
  • rkhb
    rkhb almost 10 years
    @Jon: mov [eax], bl! Not mov [eax], ebx! You want to store only one character (= one byte).