Phuc
Phuc

Reputation: 58

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

Upvotes: 3

Views: 13550

Answers (2)

naqib
naqib

Reputation: 70

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.

Upvotes: 1

rkhb
rkhb

Reputation: 14399

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

Upvotes: 2

Related Questions