Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - why segmentation fault when copying memory

I'm running ubuntu on x86_32...and I keep getting segmentation fault while running this program.

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. Please help me out ..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's at least two ways to do this:

malloc method:

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). If the size of your input changes and you forget to update the number 6, problems will occur.

The reason why you are getting a segmentation fault is because the pointer d does not point to anywhere. In your memcp function, you are trying to write this pointer but because it does not point anywhere meaningful your program crashes. In the C standard, this is called undefined behaviour, and basically it means anything can happen.

Also, it may interest you that there are already two functions available in the Standard C Library, memmove and memcpy. memmove is useful if the source and destination areas overlap. If you know they won't ever overlap, memcpy may be faster.

Lastly I would like to point out that you should not take the advice from Artur regarding uninitialised pointer usage. 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:

J.2 Undefined Behaviour

  1. The behavior is undefined in the following circumstances:
    • The value of an object with automatic storage duration is used while it is indeterminate.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...