Iterate over strings in assembly (NASM)

2020-07-30 03:25发布

问题:

I am trying to count the length of the string argv[1] in NASM assembly language. I think I'm on the right track. I have moved the address of argv[1] to register eax and now I want to move through it byte by byte and compare to the null string terminator.

Everytime I run the code it segfaults on the null comparison. Am I not getting the memory indexing correct?

*Disclaimer: This is a small part of a large homework assignment.

segment .bss

N: resd 1                 ;counter for size of argv[1]

segment .text
  global asm_main

asm_main:
  enter 0,0               ;setup
  pusha                   ;save all registers

  mov eax, dword [ebp+8]  ;argc to eax

  mov ebx, dword [ebp+12] ; address of argv to ebx
  mov eax, dword [ebx+4]  ; address of argv[1] to eax

  mov [N], dword 0        ; N = 0 

  .loop:

    add eax, [N]          ; advance index by N
    cmp eax, dword 0      ; check for end of string
    je .endloop           ; break out of the loop if we're done


    add [N], dword 1      ; N++    

    jmp .loop             ; loop back for next char

  .endloop:

popa
mov eax, 0
leave
ret

回答1:

After a few hints and the help of gdb, the loop now looks like this:

  mov [N], dword 0        ; N = 0 

  .loop:

    cmp [eax], byte 0     ; check for end of string
    je .endloop    

    add eax, dword 1      ; advance index by 1 byte
    add [N], dword 1      ; N++    

    jmp .loop             

  .endloop:

Using N to increment the index was silly. I needed to increment by 1.