Search code examples
assemblymasm

Checking if two strings are equal in assembly


The program is to check if the user entered password matches with the one specified directly in the program. Not able to understand why i always happen to get 'PASSWORD INCORRECT' when i try to input directly from the keyboard. When specifying the 'SRC' directly in the program the output seems to be perfect though.

.MODEL SMALL
.STACK 1000H

DISP MACRO MSG ;macro to display a string of characters
LEA DX,MSG
MOV AH,09H
INT 21H
ENDM

INPUT MACRO ;macro to input character by character
MOV AH,01H
INT 21H
ENDM

DATA SEGMENT 
CR EQU 0DH
LF EQU 0AH
MSG DB 'ENTER YOUR PASSWORD PLEASE : ',CR,LF,'$'
TRU DB 'PASSWORD CORRECT$'
FAL DB 'PASSWORD INCORRECT$'
SRC DB 10 DUP('$')
DEST DB 'YO$' 
LEN EQU ($-DEST)
DATA ENDS 


CODE SEGMENT
ASSUME CS:CODE,DS:DATA,ES:DATA
START:  MOV AX,DATA
    MOV DS,AX
    MOV ES,AX
    MOV SI,OFFSET SRC
    MOV DI,OFFSET DEST  
    CLD
    MOV CX,LEN
    XOR BX,BX
    DISP MSG
RE: INPUT
    MOV [SI],AL
    INC SI
    INC BX
    CMP AL,CR
    JNE RE

    CMP BX,CX ;if string lengths dont match then the strings are unequal
    JNE L1

    MOV SI,OFFSET SRC
    REPE CMPSB
    JNZ L1
L2: DISP TRU
    JMP EXIT
L1: DISP FAL
EXIT:   MOV AH,4CH
    INT 21H
CODE    ENDS
    END START

Solution

  • Your check for whether the read character is a carriage return is placed after the character has been written to the SRC buffer. So when you compare the two strings later on, SRC will contain a CR character that DEST doesn't contain.

    That is, if you entered YO you'll have DEST = 'YO$', SRC = 'YO\r', and LEN = 3.

    Here's a modified version of the input loop that works (new code is in lowercase):

    RE: INPUT
        cmp al,CR
        je got_input  ; exit the loop if we read a CR character
        MOV [SI],AL
        INC SI
        INC BX
        jmp RE
    got_input:
        inc bx     ; LEN includes the '$' character after 'YO', so increase bx by one to match that
        CMP BX,CX  ; if string lengths dont match then the strings are unequal