本文介绍了使用时,strcpy的访问冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图重塑strcpy的C函数,但是当我尝试运行它,我得到这个错误:
在brainf%ck.exe在0x00411506 未处理的异常:0000005:访问冲突写入位置0x00415760。
在 * DEST = * SRC出现的错误;
行。这里的code:
的char *的strcpy(字符* DEST,为const char * SRC){
字符* dest2 = DEST;
而(* SRC){
* DEST = * SRC;
SRC ++;
DEST ++;
}
* DEST ='\\ 0';
返回dest2;
}
编辑:哇,这是快。下面是调用code(strcpy的是mystring.c定义):
的#includemystring.h
#包括LT&;&stdio.h中GT;诠释主(){
的char * s =你好;
字符* T =ABC;
的printf(%S的strcpy(S,T));
的getchar();
返回0;
}
解决方案
的char * s =你好;
字符* T =ABC;
的printf(%S的strcpy(S,T));
编译器放在你的目标缓冲区,秒,在只读存储器,因为它是一个常数。
个char [5];
字符* T =ABC;
的printf(%S的strcpy(S,T));
应该解决这个问题。这种分配栈,它是写在目标数组。
I've tried reinventing the strcpy C function, but when I try to run it I get this error:
Unhandled exception at 0x00411506 in brainf%ck.exe: 0xC0000005: Access violation writing location 0x00415760.
The error occurs in the *dest = *src;
line. Here's the code:
char* strcpy(char* dest, const char* src) {
char* dest2 = dest;
while (*src) {
*dest = *src;
src++;
dest++;
}
*dest = '\0';
return dest2;
}
EDIT: Wow, that was fast. Here's the calling code (strcpy is defined in mystring.c):
#include "mystring.h"
#include <stdio.h>
int main() {
char* s = "hello";
char* t = "abc";
printf("%s", strcpy(s, t));
getchar();
return 0;
}
解决方案
char* s = "hello";
char* t = "abc";
printf("%s", strcpy(s, t));
The compiler placed your destination buffer, s, in read-only memory since it is a constant.
char s[5];
char* t = "abc";
printf("%s", strcpy(s, t));
Should fix this problem. This allocates the destination array on the stack, which is writable.
这篇关于使用时,strcpy的访问冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!