cstringmemmove

Mimicking memmove's behaviour


I am attempting to create a function with a similar work to memmove. I found in the man that the copying is done by including a transitionnal array to where bytes are copied first , which should not overlap with dest, then copied to destination. This the code I attempted to make (including the necessary headers):

void    *ft_memmove(void *dest, const void *src, size_t n)
{
    unsigned char p[n];
    unsigned char *p2;
    const unsigned char *p3;
    size_t i;

    p2 = dest;
    p3 = src;
    i = 0;
    while (i < n)
        *(p + i++) = *(p3++);
    while (n--)
        *(p2++) = *(p++);
    return (dest);
}

I believe the problem is related to assigning the const void array's elements to p while it is a constant or something similar. Should I use malloc or is there another possible way? Or my uderstanding of how memmove actually wroks is wrong because I found other definitions somewhere else.

I ran the previous code on this main:

int main()
{
    char s1[] = "holala";
    char s2[] = "dongo";

    ft_memmove(s1, s2, sizeof(s2));
    printf("%p,\n", s1);
}

It should've shown "donga", instead I get this error:

ft_memmove.c:17:22: error: lvalue required as increment operand
   17 |         *(p2++) = *(p++);

Solution

  • p is an array, not a pointer, so you can't increment it. Use different variables for the temporary array and the pointer, so you can increment the pointer.

    void    *ft_memmove(void *dest, const void *src, size_t n)
    {
        unsigned char temp[n];
        unsigned char *p = temp;
        unsigned char *p2;
        const unsigned char *p3;
    
        p2 = dest;
        p3 = src;
        for (sizt_t i = 0; i < n; i++) {
            *(p++) = *(p3++);
        }
        p = temp;
        while (n--) {
            *(p2++) = *(p++);
        }
        return (dest);
    }
    

    Or you could do it like the way you assigned to p in the first loop, using *(p2++) = *(p + i++)