3 ms·
I usually use strncpy and enforce null at end, that virtually is the same that does a strlcpy. But if you know how long is the source and destiny buffers (and
by Zardoz84 12y ago
I usually use strncpy and enforce null at end, that virtually is the same that does a strlcpy.
But if you know how long is the source and destiny buffers (and if you are using str[nl]cpy, probably you know it), you could use memcpy and get a much more faster copy.
- adekok 12y agostrncpy() zero-fills the array. Which seems overly wasteful. char buffer[1 << 24}] strncpy(buffer, "a", sizeof(buffer)); will set all of the array to zero, instead of just copying two bytes. And as you noted, it won't NUL terminate the string. Since strncpy() doesn't return C strings, it's not really a "C string" function. It's a horrible, inefficient bastardization which should be used by no one.
- ploxiln 12y agoMeanwhile, strlcpy() returns the length of the source. So if you just want to copy a part of the source, or you're not sure if the source is terminated past the length you want to copy, it's either wasteful or dangerous.
- wahern 12y agoThose are completely made-up objections. strlcpy also fails to fix me coffee in the morning, ergo it should be avoided.
- Zardoz84 12y agosize_t len = (src_size < dst_size) ? src_size : dst_size; memcpy (dst, src, len); // or memmove dst[len-1] = 0; So not fills unecesary 0's and it's much more faster that any str?cpy
- noselasd 12y agoYou rarely want to use strncpy. Keep in mind: 1) char buf[1024]; strncpy(buf, "hello", sizeof buf); now fills in 5 characters, and 1019 0 bytes in the buffer. (i.e. you're writing 1018 nul bytes that's usually not needed) 2) char buf[5]; strncpy(buf, "hello", sizeof buf); results in buf NOT being a string. (it isn't nul terminated). So with most use of strncpy, you'll have to also do buf[sizeof buf - 1] = 0;