Monday, 26 August 2013

MEMCPY AND MEMMOVE

#include <string.h>
#include <stdio.h>
#include<stdlib.h>
 int main()
 {

  char a[20]="vinayagam";
  char b[20]="vinayagam";
 printf("Address of A:%u",&a);
 printf("Address of B:%u",&b);
  memmove(a+5, a, 20);
   puts(a);
 memcpy(b+5, b, 20);
   puts(b);
   }
The output:

Address of A:2815980

Address of B:2815952.
vinayvinayagam
vinayvinayagam


In this program memmove handles the overlapping of source and destination,But memcpy doesn't

able to handle the overlapping of souce and destination strings.So buffer over run occurs at 'b'.

 

Reason For Not working:


Normally, a memcpy that copies downwards(Downwards means source address will be higher than destination address Ex:memcpy(0x20,0x50,30) will work

perfectly well in practice, because the natural way to do memcpy() by making it just copy things upwards will  just work even for the overlapping case but causes buffer overflow.


To Avoid Overlapping in memcpy:


We can use memcpy in the case of downwards:

Ex:
#include <string.h>
#include <stdio.h>
#include<stdlib.h>
 int main()
 {

  char a[20]="vinayagam";
  char b[20]="vinayagam";
 printf("Address of A:%u",&a);
 printf("Address of B:%u",&b);
  memmove(a+5,a,9);
   puts(a);
 memcpy(b,b+5,4);
   puts(b);
   }

The output:

Address of A:2815980

Address of B:2815952.

vinayvinayagam
agamyagam


 

No comments: