سؤال

    Str_compare PROC USES eax edx esi edi,
        string1: PTR BYTE,
        string2: PTR BYTE
    ;
    ; Compare two strings.
    ; Returns nothing, but the Zero and Carry flags are affected
    ; exactly as they would be by the CMP instruction.
    ;-----------------------------------------------------------
        mov  esi, string1
        mov  edi, string2
    L1: mov  al, [esi]
        mov  dl, [edi]
        cmp  al, 0
        jne  L2
        cmp  dl, 0
        jne  L2
        jmp  L3

    L2: inc  esi
        inc  edi
        cmp  al, dl
        je   L1

    L3: ret
    Str_compare ENDP

Against the code above, what if string1 is just byte 0 and string2 is some common string whose length is not 0?
I suppose, when cpu enter L1 at the first time, IP will jump to L2 after cmp dl, 0. inc esi will make esi point to an content-unknown byte right after the 0 byte of string1, so this program break down, right?

هل كانت مفيدة؟

المحلول

inc esi will make esi point to an content-unknown byte right after the 0 byte of string1, so this program break down, right?

Pointing to X simply means holding the address of X. It's perfectly ok to hold a value which could be interpreted as an invalid address, as long as you don't try to dereference the pointer (i.e. read from the address).

Even if you did try to read from [esi] when esi points one byte beyond string1 there would probably not be any crash. It's fairly likely that you've got other data located after string1 which also belongs to your program, and which your program therefore has access to. So reading beyond string1 will just read whatever happens to be there, up until some point where you go beyond the end of your program's data section or stack or wherever string1 happens to be located.

What happens in the Str_compare function if one string is empty (contains only a NUL-terminator) and the other is non-empty is that cmp al, dl will compare a NUL-terminator against something that is not a NUL-terminator. The conditional je L1 will therefore not jump back to L1, and instead the ret at L3 will be executed, causing the function to return. The incremented addresses in esi and edi will therefore not be dereferenced.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top