开发者

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);
开发者_Python百科    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 ..


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜