Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 423
Thokchom Avatar asked May 14 '13 21:05

Thokchom


People also ask

What is the difference between memcpy and strncpy?

strcpy () is meant for strings only whereas memcpy() is generic function to copy bytes from source to destination location.

What is the difference between memcpy and strcpy?

- memcpy() copies specific number of bytes from source to destinatio in RAM, where as strcpy() copies a constant / string into another string. - memcpy() works on fixed length of arbitrary data, where as strcpy() works on null-terminated strings and it has no length limitations.

Is memcpy faster than strcpy?

If you know the length of a string, you can use mem functions instead of str functions. For example, memcpy is faster than strcpy because it does not have to search for the end of the string. If you are certain that the source and target do not overlap, use memcpy instead of memmove .

Is memcpy safe than strcpy?

So, you should always use memcpy() because you should always know how long a string you are dealing with. Well, strcpy is safe if you know that the destination buffer is at least as big as the source buffer, even if you don't know the length of the actual string.


1 Answers

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.

like image 177
Timo Geusch Avatar answered Sep 16 '22 14:09

Timo Geusch