关于字符串长度计数的一些问题

时间:2010-07-17 16:22:45

标签: assembly nasm

我有一个关于计算字符串长度的问题。 我总是得到一些像2432这样的数字,你我传了一个像“abc”这样的字符串。

我认为问题出在这一行

mov bl, byte [esi]

但我不知道为什么。 也许这是一个字符长度为比特的东西?

问题可能是64位操作系统还是双核处理器? (我在某种程度上怀疑,因为我认为第一行“位32”应该解决问题)。

PS:这是一个练习,这就是我需要确定这样的字符串长度的原因。

代码:

bits 32
extern _printf
extern _scanf
global _main

section .data
number_frmt db 10,"%d",10,0
enter_str db "Enter some string: ", 10,0
string_frmt db "%s", 0

section .bss
entered_string resb 100

section .text

_main:
    pushad

    push dword enter_str
    call _printf
    add esp, 4

    push dword entered_string
    push dword string_frmt
    call _scanf
    add esp, 4  ;leave the entered string in the stack

    call count  ; count it and put the result to eax

    push dword eax
    push dword number_frmt
    call _printf
    add esp, 12

    popad
    ret

count:
    push esi    ;save it
    push ebx    ;save it
    mov eax, 0  ;init eax=0
    mov esi, [esp+12] ;put the entered string to esi

.loop:
    mov bl, byte [esi]  ;get the first char
    inc eax             ;eax++
    add esi,1           ;point to next char
    cmp bl,10           ;is it new line?
    jne .loop           ;if not loop
    dec eax             ;eax-- (because of newline at the end)
    pop ebx             ;retrieve ebx
    pop esi             ;retrieve esi
    ret

2 个答案:

答案 0 :(得分:4)

cmp bl,10           ;is it new line?

应该是

cmp bl,0

因为c / c ++字符串每次都以0结束/终止,所以你实际上在内存中搜索了下一个10的随机位置。

答案 1 :(得分:1)

使用scanf可能不是一件好事,因为它会让人感到困惑,用get来切换,新行也是有效字符,并且应该算作计数的一部分。字符串是NUL终止(自动)

count:
    push esi    ;save it
    push ebx    ;save it
    xor eax, eax; initialize it to zero
    mov esi, [esp+12] ;put the entered string to esi

.loop:
    mov bl, byte [esi]  ;get the first char

    cmp bl, bl          ;set the flags
    jz  .out            ;nul character

    inc eax
    jmp .loop

    pop ebx             ;retrieve ebx
    pop esi             ;retrieve esi

    ret
相关问题