Q18 Write your own function of memmove().

User defined function of memmove().

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void own_memmove(void *to, const void *from, int n)

{

        unsigned char *ptr = (unsigned char *)to;

        unsigned char *ptr1 = (unsigned char *)from;

        /* Checking overlap condition */

        ptr1 = ptr1 + n;

        while((ptr1 != from) && (- -ptr1 != to));

        if(ptr1 != from)

        {

                ptr1 = (unsigned char *)from;

                ptr1 = ptr1 + n;

                ptr = ptr + n;

                while(n– != 0)

                {

                        *- -ptr = *- -ptr1;

                }

        }

        else

        {

                while(n- – != 0)

                {

                        *ptr++ = *ptr1++;

                }

        }

}

 

int main()

{

        char *ptr = NULL;

        char *ptr1 = NULL;

        char *ptr2 = NULL;

        char *ptr3 = NULL;

        ptr = (char*)malloc(30);

        ptr1 = (char*)malloc(30);

        ptr2 = (char*)malloc(30);

        ptr3 = (char*)malloc(30);

        printf(“Enter value of ptr nad ptr1\n”);

        gets(ptr);

        strcpy(ptr1,ptr);

        strcpy(ptr2,ptr);

        strcpy(ptr3,ptr);

        printf(“ptr after memmove\n”);

        /* Destination is greater than source */

        own_memmove(ptr+5, ptr+1, 10);

        puts(ptr);

        printf(“ptr1 after memmove\n”);

        /* Destination is less than source */

        own_memmove(ptr1+1, ptr1+5, 10);

        puts(ptr1);

        printf(“ptr2 after memmove\n”);

        /* No overlap between destination and source */

        own_memmove(ptr2+1, ptr2+12, 10);

                puts(ptr2);

        printf(“ptr3 after memmove\n”);

        /* No overlap between destination and source */

        own_memmove(ptr3+12, ptr3+1, 10);

        puts(ptr3);

        free(ptr);

        free(ptr1);

        free(ptr2);

        free(ptr3);

        return 0;

}

Output:

$ ./a.exe

Enter value of ptr nad ptr1

ABCDEFGHIJKLMNOPQRSTUVWXYZ

ptr after memmove

ABCDEBCDEFGHIJKPQRSTUVWXYZ

ptr1 after memmove

AFGHIJKLMNOLMNOPQRSTUVWXYZ

ptr2 after memmove

AMNOPQRSTUVLMNOPQRSTUVWXYZ

ptr3 after memmove

ABCDEFGHIJKLBCDEFGHIJKWXYZ

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.