简体   繁体   English

为什么复制内存时出现分段错误

[英]why segmentation fault when copying memory

I'm running ubuntu on x86_32...and I keep getting segmentation fault while running this program. 我在x86_32上运行ubuntu ...,并且在运行该程序时不断出现分段错误。

enter code here
#include<stdio.h>
#include<stddef.h>
char *memcp(char *dest, const char *src, size_t n)
{

    char *dp = dest;
    const char *sp = src;
    while(n--)
        *dp++ = *sp++;
    return dest;

}

int main()
{

    char *s = "abcde";
    char *d;
    char *r = memcp(d,s,6);
    printf("%s",r);

    return(0);
}

The problem with this code is that it is running on my friend's x86_64 machine on windows as well as ubuntu. 此代码的问题在于,它在Windows和ubuntu上我朋友的x86_64计算机上运行。 Please help me out .. 请帮帮我..

There's at least two ways to do this: 至少有两种方法可以做到这一点:

malloc method: malloc方法:

int main(void)
{
    char *s = "abcde";
    char *d = malloc(6);
    char *r = memcp(d, s, 6);
    printf("%s",r);

    free(d);
    return(0);
}

Array method: 数组方法:

int main(void)
{
    char *s = "abcde";
    char d[6];
    memcp(d, s, 6);

    return 0;
}

Note that it is generally not a good idea to hard code buffer lengths into your code (for example, you are hardcoding 6). 请注意,将缓冲区长度硬编码到代码中通常不是一个好主意(例如,您正在硬编码6)。 If the size of your input changes and you forget to update the number 6, problems will occur. 如果输入的大小发生变化,而您忘记更新数字6,则会出现问题。

The reason why you are getting a segmentation fault is because the pointer d does not point to anywhere. 出现分段错误的原因是因为指针d没有指向任何地方。 In your memcp function, you are trying to write this pointer but because it does not point anywhere meaningful your program crashes. 在您的memcp函数中,您尝试编写此指针,但是因为它没有指向有意义的程序崩溃的任何位置。 In the C standard, this is called undefined behaviour , and basically it means anything can happen. 在C标准中,这称为未定义行为 ,基本上它意味着任何事情都可能发生。

Also, it may interest you that there are already two functions available in the Standard C Library, memmove and memcpy . 另外,您可能会感兴趣的是,标准C库中已经有两个函数memmovememcpy memmove is useful if the source and destination areas overlap. 如果源区域和目标区域重叠,则memmove很有用。 If you know they won't ever overlap, memcpy may be faster. 如果您知道它们永远不会重叠,则memcpy可能会更快。

Lastly I would like to point out that you should not take the advice from Artur regarding uninitialised pointer usage. 最后,我想指出的是,您不应该接受Artur关于未初始化指针使用的建议。 You should never rely on the value of an uninitialised pointer and doing so means your program's behaviour is not well-defined. 您永远不要依赖未初始化指针的值,这样做意味着程序的行为没有明确定义。 Annex J of the C language specification mentions the following that is undefined behaviour : C语言规范的附件J提到了以下未定义行为

J.2 Undefined Behaviour J.2未定义行为

  1. The behavior is undefined in the following circumstances: 在以下情况下,行为是不确定的:
    • ...
    • The value of an object with automatic storage duration is used while it is indeterminate. 具有自动存储持续时间的对象的值在不确定时使用。
    • ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM