c - 我不确定为什么我的 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 代码在它下面被注释掉了。我非常感谢任何帮助,谢谢。
解决方案
推荐阅读
- python - 如何定义具有所有可能数字组合的数组
- c# - Asp mvc 将 Int32 类型转换为列表
- javascript - 如何在 AirConsole 控制器上制作动画按钮?
- google-analytics-api - ga:adCost 在查询生成器中返回 0
- r - optim 中的目标函数评估为长度 2 而不是 1
- java - Apache MINA SSHD java.security.InvalidKeyException:SHA-1 摘要算法的安全强度不足以满足此密钥大小
- php - 如何使期权价值包含超过1个价值?
- java - Rest - 响应中的 MediaType 与请求中的相同
- javascript - 通过单击单词播放 mp3 文件
- php - 使用动态生成的索引和值归档或平衡数组