Access violation writing location is occuring in Assembly

I'm programming in Assembly and the following error occurred to me:

Exception thrown at 0x00B71792 in Application1.exe: 0xC0000005: Access violation writing location 0x00B76BED.

Unhandled exception at 0x00B71792 in Application1.exe: 0xC0000005: Access violation writing location 0x00B76BED.

I'm using Visual Studio to program. Here follows my code:

char *strCat(char *dest, char *src) {
    __asm {
        xor eax, eax
        mov ecx, 0xffffffff
        mov esi, src
        mov edi, dest
        mov al, 0
        cld
        repne scasb
        dec edi
    L0 :
        lodsb
        stosb
        test al, al
        jne L0
        mov eax, edi
    };
}

The error ocurr in stosb instruction according the debug.

In my point of view the code is correct. Couldn't find the error.

Upvotes: 1

Views: 3373

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

The issue with the crash is that you're trying to concatenate characters onto a string-literal. This is undefined behavior in C++ (and C).

To call your function safely, you have to

1) Ensure that your destination buffer is big enough to hold the concatenated string, and

2) The destination buffer is writable memory, not a string-literal.

To make the memory writable, one way is to simply declare a char array that is big enough to hold the entire concatenated string:

char destination[100] = "abc";
strCat(destination, "123");

Upvotes: 2

Related Questions