Search code examples
c++assemblyx86inline-assembly

: 0xC0000005: Access violation writing location 0x00000000 C++ with inline assembly


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


Solution

  • 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).