tags:

views:

41

answers:

2

Hi,

I have a problem about counting the length of a string. I always get some number like 2432, thou I pass a string like "abc".

I think the problem is in this line

mov bl, byte [esi]

but I would not know why. Maybe it is something with character length in bits?

Could the problem be a 64bit operating system or dual core processor? (which I somehow doubt, because I think the first line "bits 32" should solve the problem).

PS.: This is an exercise, that is why I need to determine the length of the string like this.

The code:

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
+4  A: 
cmp bl,10           ;is it new line?

should be

cmp bl,0

because c/c++ strings are everytime ended/terminated by a 0, so you have in fact searched for an random position in the memory where the next 10 is.

Quonux
+1  A: 

Using scanf is probably not a good thing as it confuses matters, switch that with gets, also new lines are valid characters, and should be counted as part of your count. Strings are NUL terminated (automatically)

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
Elf King