Friday, July 14, 2017

Remember about memcpy/memmove, strcpy/strncpy and malloc/calloc..!

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..


About 'const' qualifier...

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change value of const variable by using pointer ). The result is implementation-defined if an attempt is made to change a const.

When we make some pointer as constant, its restricting the access to that memory location through that pointer variable only which means still you will be able to make any modification using other means.

#include

void main()
{
  int i=10, j=20;

  const int *p = &i;      // Pointer to a constant
  int * const p1 = &i;    // Constant pointer to an integer variable
  const int * const p2 = &j;  // Constant pointer to an integer constant 

  *p = NULL;

  p1 = NULL;

  *p2 = 25;

  i = 30;      // valid because we are accessing directly not through pointer

  printf("%d\n", p);
}

Linux 64-bit machine output:

const.c: In function `main':
const.c:10: error: assignment of read-only location
const.c:10: warning: assignment makes integer from pointer without a cast
const.c:12: error: assignment of read-only variable `p1'
const.c:14: error: assignment of read-only location'


Other easy way to remember is how the const keyword is assosiated in the variable declaration statement, as a prefix. const int * OR int const *  refers to value and (int * const ptr) refers to address. I mean, after the keyword const, is the value is there or address is there will be the actual constant (address or value). const int * const ptr where const is associated with both and hence both are constants.

Reference:
http://www.geeksforgeeks.org/const-qualifier-in-c/