Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 516
Phuc Avatar asked Apr 28 '26 17:04

Phuc


2 Answers

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

like image 113
rkhb Avatar answered Apr 30 '26 12:04

rkhb


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.

like image 36
naqib Avatar answered Apr 30 '26 12:04

naqib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!