Search code examples
assemblyinfinite-loopx86-16instructionsemu8086

While search each character of a string and change it in emu8086 how to end infinite loop?


When compare and change a character of a string to another character, it is not change last character.

But when i change cx to 12 is working but it is stuck infinite loop

.model small
.stack 64
.data
        dizi1 db 'bilgisayai'
.code
            mov ax,@data
            mov ds,ax
            mov es,ax

            lea di,dizi1

            mov cx,10
            mov al,'i'
            mov bl,'#'

ara: repne  scasb
            jnz cik
            mov [di-1],bl
            loop ara

cik:        mov ah,4ch
            int 21h
            end

i want to change 'i's in the string to '#' but last 'i' doesn't change.


Solution

  • Don't use LOOP

    What happens when you set CX=10 ==> "Not found"

    'bilgisayai'

    When scasb finds the 1st 'i', CX is 8 and the loop instruction will decrement down to 7, but continues fine. However for scasb your string is now 1 character shorter!

    'bi ... lgisaya'

    When scasb finds the 2nd 'i', CX is 4 and the loop instruction will decrement down to 3, but continues fine. However for scasb your string is again 1 character shorter!

    'bi ... lgi ... say'

    scasb will process a further 3 bytes, no longer finds an 'i' and the program exits.

    What happens when you set CX=12 ==> "Infinite loop"

    'bilgisayai??'

    When scasb finds the 1st 'i', CX is 10 and the loop instruction will decrement down to 9, but continues fine. However for scasb your string is now 1 character shorter!

    'bi ... lgisayai?'

    When scasb finds the 2nd 'i', CX is 6 and the loop instruction will decrement down to 5, but continues fine. However for scasb your string is again 1 character shorter!

    'bi ... lgi ... sayai'

    When scasb finds the 3rd 'i', CX is 0 and the loop instruction will decrement down to 65535 , and continues 'forever'.

    Solution.

    Replace loop by next code:

      lea  di, dizi1
      mov  cx, 10       ;Length of the string (true length!)
      mov  al, 'i'
      mov  bl, '#'    
    ara:
      repne scasb
      jnz  cik
      mov  [di-1], bl
      test cx, cx       ;If CX=0 then SCASB was at end of string
      jnz  ara
    cik: