3 ms·
snprintf is also slower. It has to parse the format string. Just use strncpy and NUL-terminate the buffer. It's not hard. Write a two line function to do it fo
by jjnoakes 11y ago
snprintf is also slower. It has to parse the format string.
Just use strncpy and NUL-terminate the buffer. It's not hard. Write a two line function to do it for you, and use that function in place of strncpy.
- _kst_ 11y agodest[0] = '\0'; strncat(dest, src, size);
- jjnoakes 11y agoSure. Or: strncpy(dest, src, size); dest[size - 1] = '\0';
- masklinn 11y ago> Just use strncpy and NUL-terminate the buffer. It's not hard. Just as it's not hard to not dereference null pointers, not double-free allocations and a truckload of other mindless drudgery which history shows humans won't reliably get right all the time. Not to mention checking for copy truncation with strncpy is error-prone, you've got to check whether it points to a `\0` before you manually null-terminate it, providing more chances to get it wrong. > snprintf is also slower. It has to parse the format string. How about worrying about that when snprintf actually shows up in profiles and there's no algorithmic way to improve the situation and strncpy is a significant improvement?
- jjnoakes 11y agoBut if you read my actual comment, I suggest not using strncpy everywhere. Use it once. In a 2-line wrapper. And use the wrapper everywhere. No human reliability to worry about.