0

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\n");
        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\n");
        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 \nDestination: %s, size: %d\n", 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!

pr123
  • 19
  • 3

1 Answers1

0

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362