Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting a character into a string in NASM

I’m trying to do a very simple assembly exercise with NASM, but the everything I’ve been taught suggests this should work, yet it doesn’t.

It’s supposed to iterate through the string "Burning The Midnight Oil," and place the characters into dest in reverse, so that it prints "liO thgindiM ehT gninruB" to the output. It does not. It just prints the string of x’s, no matter what I do to change it.

What am I missing here? How can I edit the contents of dest after I create it? I am so tired.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

global _start
section .text
_start: mov rax, 1
        mov rdi, 1
        mov rsi, dest
        mov rdx, len
        syscall
        mov rax, 60
        xor rdi, rdi
        syscall
section .data
src:    db 'Burning The Midnight Oil', 10
dest:   db 'xxxxxxxxxxxxxxxxxxxxxxxx', 10
len:    equ $ - dest

        xor rcx,rcx
        mov rcx,len
        mov rsi,len
loopstart:
        sub rsi,rcx
        mov al,[src+rcx]
        mov [dest+rsi],al
        dec rcx
        jnz loopstart

>Solution :

The program starts executing at the _start label. You immediately display and exit even before processing the string! Move the loop code at _start:.

Your len: equ $ - dest includes the newline code (10). That’s wrong! You must leave that byte where it is.

len:    equ ($ - dest) - 1   ; Iteration count

Writing to the last position of the string requires using "Length – 1", therefore write mov [dest+rsi-1], al

Copying the string just requires using two offsets: one incrementing and the other decrementing until zero:

_start:
    mov  rdi, len
    xor  esi, esi
loopstart:
    mov  al, [src + rsi]
    mov  [dest + rdi - 1], al
    dec  rdi
    jnz  loopstart

    mov rax, 1
    mov rdi, 1
    mov rsi, dest
    mov rdx, len
    syscall
    mov rax, 60
    xor edi, edi
    syscall
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading