by nneonneo · 8y ago · 0 comments
dst[sizeof(dst)-1] = 0;
or memset the array to zero beforehand. You are not guaranteed to have a zero at the end of the input buffer otherwise (neither local variable arrays nor malloc’d arrays are guaranteed to be zeroed).strncpy sucks for a second reason: it writes n bytes no matter what the source is. That means if you write
char buffer[16384];
strncpy(buffer, “hello”, sizeof(buffer)-1);
buffer[sizeof(buffer)-1] = 0;
this will fill 16K of memory with zeroes despite only needing to copy a 6-byte string.strlcpy/strlcat do the right thing (copy up to n-1 bytes and null-terminate); shame they aren’t standardized. In their absence, I suggest snprintf instead:
snprintf(buffer, sizeof(buffer), “%s”, src);
Because snprintf returns the number of bytes that would be written, it can be used to detect overlong input strings, reallocate the buffer as necessary, and also to implement efficient concatenation. It’s also surprisingly fast in most implementations.But beware of old MS _snprintf:
https://docs.microsoft.com/en-us/previous-versions/visualstu...
Thumbing through previous submissions of this domain with discussion, this seems to be a pattern.
If you just do string manipulation, memncpy is faster.
If you need to convert data type, like int to string, then use snprintf.
See https://gist.github.com/nneonneo/f9dc5c1d1d342d25eae47d56dba... for a test harness. On my Mac, with a 16-byte string, 10 million loops:
memcpy: 77406 us
strlcpy: 101956 us
strncpy: 177247 us
sprintf: 730819 us
snprintf: 699844 us
memcpy smokes sprintf - around 10x faster. The vast majority of sprintf's time is spent in setup; for large strings, the gap closes substantially.