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
472 views
in Technique[技术] by (71.8m points)

pointers - memmove implementation throws segmentation fault while copying a character array

Hi I tried to write my own version of memmove and I find the following code resulting in a segmentation fault. It would be great if someone could help me figure out why this behavior would occur!

However, when I use something like: char source[20] = "Hello, this is Piranava", the code works fine!

void *memmoveLocal(void *dest, const void *src, unsigned int n)
{
char *destL = dest;
const char *srcL = src;
int i = 0;

if(dest == NULL || src == NULL)
{
    return NULL;
}
else
{
    // if dest comes before source, even if there's an overlap, we should move forward
    // because if there's an overlap (when dest < src) and we move backward, we'd overwrite the overlapping bytes in src
    if(destL < srcL)
    {
        printf("Forward
");
        while(i < n)
        {
            destL[i] = srcL[i];
            i++;
        }
    }
    else // in all other cases (even if there's overlap or no overlap, we can move backward)
    {
        printf("Backward
");
        i = n - 1;
        while(i >= 0)
        {
            destL[i] = srcL[i];
            i--; 
        }
    }
}

return dest;
}

void main()
{
    char *source = "Hello, this is ABC"; 

    char *destination = malloc(strlen(source)+1);

    memmoveLocal(source+5, source, 5);

    printf("Source: %s 
Destination: %s, size: %d
", source, destination, strlen(destination));
}

However, if I replace

char *source = "Hello, this is ABC";

with

char source[20] = "Hello, this is ABC"; 

, it works fine!

question from:https://stackoverflow.com/questions/65897346/memmove-implementation-throws-segmentation-fault-while-copying-a-character-array

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

1 Reply

0 votes
by (71.8m points)

memmoveLocal(source+5, source, 5);

You are trying to overwrite a string literal, which is not writable.

Did you intend to memmoveLocal(destination, source+5, 5) instead?

char source[20] = "Hello, this is ABC";

That turns source from a string literal into a char[] array initialized with a string literal. The array is writable, so your program no longer crashes.


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

...