首页 > 解决方案 > 我不确定为什么我的 strncpy 函数中途中断?

问题描述

我在 Visual Studio 中的 _asm 代码遇到以下错误:“HW7.exe 中 0x00431BCF 的第一次机会异常:0xC0000005:访问冲突写入位置 0x00000000。”

#include <stdio.h>
#include <stddef.h>

// Function to implement strncpy() function
char* strncpy(char* destination, const char* source, size_t num)
{

    _asm {
            push    ebp
            mov ebp, esp
            sub esp, 208; 000000d0H
            push    ebx
            push    esi
            push    edi
            lea edi, DWORD PTR[ebp - 208]
            mov ecx, 52; 00000034H
            mov eax, -858993460; ccccccccH
            rep stosd
            cmp DWORD PTR[destination], 0
            jne label_3
            xor eax, eax
            jmp label_4
        label_3:
            mov eax, DWORD PTR[destination]
            mov DWORD PTR[ebp-08h], eax
        label_2:
            mov eax, DWORD PTR[source]
            movsx   ecx, BYTE PTR[eax]
            test    ecx, ecx
            je label_1
            mov eax, DWORD PTR[num]
            mov DWORD PTR[ebp-0D0h], eax
            mov ecx, DWORD PTR[num]
            sub ecx, 1
            mov DWORD PTR[num], ecx
            cmp DWORD PTR[ebp-0D0h], 0
            je label_1
            mov eax, DWORD PTR[destination]
            mov ecx, DWORD PTR[source]
            mov dl, BYTE PTR[ecx]
            mov BYTE PTR[eax], dl
            mov eax, DWORD PTR[destination]
            add eax, 1
            mov DWORD PTR[destination], eax
            mov eax, DWORD PTR[source]
            add eax, 1
            mov DWORD PTR[source], eax
            jmp label_2
        label_1:
            mov eax, DWORD PTR[destination]
            mov BYTE PTR[eax], 0
            mov eax, DWORD PTR[ebp-08h]
        label_4:
            pop edi
            pop esi
            pop ebx
            mov esp, ebp
            pop ebp
            ret 0


    }
/*
    // return if no memory is allocated to the destination
    if (destination == NULL)
    return NULL;
    // take a pointer pointing to the beginning of destination string
    char* ptr = destination;
    // copy first num characters of C-string pointed by source
    // into the array pointed by destination
    while (*source && num--)
    {
    *destination = *source;
    destination++;
    source++;
    }
    // null terminate destination string
    *destination = '\0';
    // destination is returned by standard strncpy()
    return ptr;
*/

}
// Implement strncpy() function in C
int main(void)
{
    /*
    char* source = "Crisp Rat";
    char destination[12];
    */
    /*
    char* source = "Christians Later";
    char destination[12];
    */
    char* source = "Huge Ackman";
    char destination[12];
    size_t num = 11;
    // Copies the first num characters of source to destination
    printf("%s\n", strncpy(destination, source, num));
    return 0;
}

我已经单步执行了代码,错误发生在指令“mov byte ptr[eax],dl”处。我的与 asm 代码等效的 C 代码在它下面被注释掉了。我非常感谢任何帮助,谢谢。

标签: cassemblyvisual-c++x86inline-assembly

解决方案


推荐阅读