Skip to content

Commit a7adfd4

Browse files
committed
Optimized version of safe_strcpy()
Note: We should replace most case of safe_strcpy() with strmake() to avoid the not needed zerofill.
1 parent 92d2cea commit a7adfd4

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

include/m_string.h

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -249,14 +249,15 @@ static inline void lex_string_set3(LEX_CSTRING *lex_str, const char *c_str,
249249
*/
250250
static inline int safe_strcpy(char *dst, size_t dst_size, const char *src)
251251
{
252-
memset(dst, '\0', dst_size);
253-
strncpy(dst, src, dst_size - 1);
254-
/*
255-
If the first condition is true, we are guaranteed to have src length
256-
>= (dst_size - 1), hence safe to access src[dst_size - 1].
257-
*/
258-
if (dst[dst_size - 2] != '\0' && src[dst_size - 1] != '\0')
259-
return 1; /* Truncation of src. */
252+
DBUG_ASSERT(dst_size > 0);
253+
/* Note, strncpy will zerofill end of dst if src shorter than dst_size */
254+
strncpy(dst, src, dst_size);
255+
if (dst[dst_size-1])
256+
{
257+
/* Ensure string is zero terminated */
258+
dst[dst_size-1]= 0;
259+
return 1;
260+
}
260261
return 0;
261262
}
262263

0 commit comments

Comments
 (0)