memcpy and memmove
These memory handling functions make us to confuse when anybody asks about the same. Better to keep in my blog for me...!
Among these, memmove handles memory overlapping but memcpy does not.
int main ()
{
char str1[]="Mera Bharat Mahan";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1);
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
Output is:Mera Bharat MahanMera Bharat Mahancopy successful
Look at the following code snap.
int main ()
{
char str[] = "memmove can be very useful......";
memmove(str+20,str+15,11);
puts (str);
return 0;
}
Output is: memmove can be very very useful
If we change the above code to memcpy(), then ,
int main ()
{
char str[] = "memmove can be very useful";
memcpy(str+20,str+15,5);
puts (str);
return 0;
}
output: memmove can be very very l
In case of memcpy, when address gets overlapped, then the data copy process starts from the beginning of src string (2nd parameter). Hence memcpy is not a better function to use when there is a possibility of address overlaps..
No comments:
Post a Comment