Edit: I've added the source for the example.
I came across this example:
char source[MAX] = "123456789"; char source1[MAX] = "123456789"; char destination[MAX] = "abcdefg"; char destination1[MAX] = "abcdefg"; char *return_string; int index = 5; /* This is how strcpy works */ printf("destination is originally = '%s'\n", destination); return_string = strcpy(destination, source); printf("after strcpy, dest becomes '%s'\n\n", destination); /* This is how strncpy works */ printf( "destination1 is originally = '%s'\n", destination1 ); return_string = strncpy( destination1, source1, index ); printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
Which produced this output:
destination is originally = 'abcdefg' After strcpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After strncpy, destination1 becomes '12345fg'
Which makes me wonder why anyone would want this effect. It looks like it would be confusing. This program makes me think you could basically copy over someone's name (eg. Tom Brokaw) with Tom Bro763.
What are the advantages of using strncpy()
over strcpy()
?
strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string. If destination string length is less than source string, entire/specified source string value won't be copied into destination string in both cases.
"strcpy does not know the size of the destination buffer to which it is writing". A function knows nothing, it's the programmer who makes sure the buffer is large enough. strncpy doesn't know anything either. It's the programmer telling it the size.
Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk. If the destination string is not large enough to store the source string then the behavior of strcpy() is unspecified or undefined.
The strncpy() function copies count characters of string2 to string1 . If count is less than or equal to the length of string2 , a null character (\0) is not appended to the copied string. If count is greater than the length of string2 , the string1 result is padded with null characters (\0) up to length count .
The strncpy()
function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a short fixed-sized array (14 bytes), and a nul-terminator was only used if the filename was shorter than the array.
That's what's behind the two oddities of strncpy()
:
For a "safer strcpy()
", you are better off using strncat()
like so:
if (dest_size > 0) { dest[0] = '\0'; strncat(dest, source, dest_size - 1); }
That will always nul-terminate the result, and won't copy more than necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With