-1

I've been writing this code to implement the C "strcmp()" function using C/C++ with embedded assembly code like this

bool myStrCmp(char* mystr1, char* mystr2) {
    if (myStrLen(mystr1) != myStrLen(mystr1)) return false;
    char s1[100], s2[100];
    strcpy_s(s1, mystr1);
    strcpy_s(s2, mystr2);
    int i = 0;
    int flag = 1;
    _asm mov ecx, flag;
    _asm 
    {
        push esi
        mov esi,i
      startCmp:
        mov al,s1[esi]
        mov dl,s2[esi]
        cmp al,NULL
            je endCmp
        cmp al,dl
            jne zeroFlag
        inc [esi]
        jmp startCmp
      zeroFlag:
         mov ecx,0
       endCmp:
            pop esi
    }
    _asm mov flag, ecx

    return flag == 1;

}

However, there is an exception at the exact line of jne zeroFlag saying : 0xC0000005: Access violation writing location 0x00000000

this exception happens whenever I enter a similar charecters in the first and second string generally

I have no idea why does this happen

rustyx
  • 80,671
  • 25
  • 200
  • 267

2 Answers2

2

It seems your debugger stops at the last instruction before the one where an exception occurred. The error is actually at the next line:

inc [esi]

That tries to increment a value stored at address esi. Since esi is 0, incrementing a value at address 0 results in an access violation.

To increment esi itself, simply write:

inc esi

With that said, there's no need to copy C-strings into temporary arrays, you can compare them in-place (and you can optimize the process by comparing in dwords, falling back to a byte compare in the last chunk).

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • it worked..thanks so much :)...regarding the optimization I'll leave it to a later time since I'm so close to the deadline right now with some other assignments to submit as well – HuangLinBao Apr 18 '21 at 16:56
1
        cmp al,dl
        jne zeroFlag

So, you fault on the jne instruction with address NULL. This is literally impossible. Remembering how the processor works, it actually faulted on the previous instruction and IP points to the next one; if the debugger doesn't adjust for this it faulted on the cmp instruction, which is equally impossible.

Only one possibility. The code your running is not the code you see in the debugger. Rebuild all, and fix your compilation errors, and try again.

You should just replace this with

bool myStrCmp(char* mystr1, char* mystr2) {
    return 0 == strcmp(mystr1, mystr2);
}

You can't beat the builtin.

Joshua
  • 40,822
  • 8
  • 72
  • 132