Wednesday, October 20, 2010

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 and you...!

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 Mahan
Mera Bharat Mahan
copy 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
eginning of src string (2nd parameter). Hence memcpy is not a better function to use when
here is a possibility of address overlaps.



strcpy() and strncpy()

strncpy(str1, str2, 10);

The major drawback of strncpy() is, when u r copying data from str2 to str1, if the number of characters if less
han or equal to string length of str2, then the NULL character of str2 will not be appended and hence the values
fter strlen(str2) will remains same as it is.


void main ()
{
char ptr[] = "Raghu";
char str[] = "Pramod Mathur";
printf("%s\n", strncpy(str,ptr,5));
}

Output will be ---- Raghud Mathur

void main ()
{
char ptr[] = "Raghu";
char str[] = "Pramod Mathur";
printf("%s\n", strncpy(str,ptr,6));
}

output will be ---- Raghu


malloc() and calloc()

The difference between malloc and calloc also could be one of the interview question. Even though if we have worked 4+ years in C programming itself, it doesnt mean that we definitely used calloc and many other functions. Also, it is in out hand itself about how we utilise the library functions. Better always to use most of the functionalities of C to becaome familiar.

When you allocate a memory to a pointer using calloc, be default, the content in the memory location, will be NULL. But whereas in the case of malloc, it is not. Thats the difference between malloc and calloc.

-------------------

Please let me know if any of u found mistakes : drop a mail to pramoda.ma@gmail.com...

Gud luckckckckck......

----

1 comment:

  1. For difference between malloc and calloc, its good that you highlighted small difference but neglected the major difference which is more worth to differentiate those two. its the number of blocks that calloc allows you to allocate. And in calloc by default it doesn't initialize to Null, i think its zero.. Sri here...

    ReplyDelete