Iterate over strings in assembly (NASM)

风流意气都作罢 提交于 2020-03-20 19:35:32

问题


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.



来源:https://stackoverflow.com/questions/40646213/iterate-over-strings-in-assembly-nasm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!