David Strong points out here
that some popular implementations of strncpy(dst,src,n) are quite
inefficient when strlen(src) is much less than n, because they don't
optimize the zero-pad step that is required by the standard.
It looks to me like we have a good number of places that are using
either StrNCpy or strncpy directly to copy into large buffers that
we do not need full zero-padding in, only a single guaranteed null
byte. While not all of these places are in performance-critical
paths, some are. David identified set_ps_display, and the other
thing that's probably significant is unnecessary use of strncpy
for keys of string-keyed hash tables. (We used to actually need
zero padding for string-keyed hash keys, but that was a long time ago.)
I propose adding an additional macro in c.h, along the lines of
#define StrNCopy(dst,src,len) \
char * _dst = (dst); \
Size _len = (len); \
if (_len > 0) \
const char * _src = (src); \
Size _src_len = strlen(_src); \
if (_src_len < _len) \
memcpy(_dst, _src, _src_len + 1); \
memcpy(_dst, _src, _len - 1); \
_dst[_len-1] = '\0'; \
} while (0)
Unlike StrNCpy, this requires that the source string be null-terminated,
so it would not be a drop-in replacement everywhere. Also, it could be
a performance loss if strlen(src) is much larger than len ... but that
is not usually the case for the places we'd want to apply it.
Thoughts, objections? In particular, is the name OK, or do we need
something a bit further away from StrNCpy?
regards, tom lane
---------------------------(end of broadcast)---------------------------
TIP 3: Have you checked our extensive FAQ?