使用strcpy时访问冲突?

Jav*_*ier 2 c strcpy

我尝试重新发明strcpy C函数,但是当我尝试运行它时,我收到此错误:

Unhandled exception at 0x00411506 in brainf%ck.exe: 0xC0000005: Access violation writing location 0x00415760.
Run Code Online (Sandbox Code Playgroud)

*dest = *src;行发生错误.这是代码:

char* strcpy(char* dest, const char* src) {
    char* dest2 = dest;
    while (*src) {
        *dest = *src;
        src++;
        dest++;
    }
    *dest = '\0';
    return dest2;
}
Run Code Online (Sandbox Code Playgroud)

编辑:哇,那很快.这是调用代码(strcpy在mystring.c中定义):

#include "mystring.h"
#include <stdio.h>

int main() {
    char* s = "hello";
    char* t = "abc";
    printf("%s", strcpy(s, t));
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 15

char* s = "hello";
char* t = "abc";
printf("%s", strcpy(s, t));
Run Code Online (Sandbox Code Playgroud)

编译器将目标缓冲区s放在只读内存中,因为它是常量.

char s[5];
char* t = "abc";
printf("%s", strcpy(s, t));
Run Code Online (Sandbox Code Playgroud)

应该解决这个问题.这会在堆栈上分配目标数组,这是可写的.


Jon*_*eet 7

显而易见的潜在问题是您的输出缓冲区没有足够的内存分配,或者您已经传入了NULL dest.(可能不适用src或之前它会失败.)

请提供一个简短但完整的程序来重现问题,我们可以检查......

这是一个在Windows上为我敲响的例子:

#include <stdlib.h>

char* strcpy(char* dest, const char* src) {
    char* dest2 = dest;
    while (*src) {
        *dest = *src;
        src++;
        dest++;
    }
    *dest = '\0';
    return dest2;
}

void main() {
    char *d = malloc(3);
    strcpy(d, "hello there this is a longish string");
}
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,我必须超过实际分配的内存量才能引发程序死亡 - 只是"hello"没有崩溃,尽管它肯定可能取决于编译器和执行环境的各个方面.