What is the difference between memcpy() and strncpy() given the latter can easily be a substitute for the former?

Thokchom picture Thokchom · May 14, 2013 · Viewed 9.5k times · Source

What is the significant difference between memcpy() and strncpy()? I ask this because we can easily alter strncpy() to copy any type of data we want, not just characters, simply by casting the first two non-char* arguments to char* and altering the third argument as a multiple of the size of that non-char type. In the following program, I have successfully used that to copy part of an integer array into other, and it works as good as memcpy().

 #include <stdio.h>
    #include <string.h>


    int main ()
    {
    int arr[2]={20,30},brr[2]={33,44};
    //memcpy(arr,brr,sizeof(int)*1);
    strncpy((char*)arr,(char*)brr,sizeof(int)*1);
    printf("%d,%d",arr[0],arr[1]);

    }

Similarly, we can make it work for float or other data-type. So what's the significant difference from memcpy()?

PS: Also, I wonder why memcpy() is in string.h header file, given nearly all of the library functions there are related to character strings, while memcpy() is more generic in nature. Any reason?

Answer

Timo Geusch picture Timo Geusch · May 14, 2013

The simple difference is that memcpy() can copy data with embedded null characters (aka the string terminator in C-style strings) whereas strncpy() will only copy the string to the maximum of either the number of characters given or the position of the first null character (and pad the rest of the strings with 0s).

In other words, they do have two very different use cases.