我有一个关于计算字符串长度的问题。我总是收到一些数字,例如2432,您传递了一个字符串,例如“ abc”。
我认为问题在于
mov bl, byte [esi]
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么。也许是字符长度以位为单位的东西?
问题可能出在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
Run Code Online (Sandbox Code Playgroud)
cmp bl,10 ;is it new line?
Run Code Online (Sandbox Code Playgroud)
应该
cmp bl,0
Run Code Online (Sandbox Code Playgroud)
因为c / c ++字符串每次都以0结尾/终止,所以实际上您已经在内存中搜索了下一个10所在的随机位置。