From a118928dee0874eef98be81531a98577c1ae3f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=B6ttsche?= Date: Tue, 5 Jan 2021 14:44:09 +0100 Subject: [PATCH] XUtils: add safe strncpy implementation The standard strncpy fails to null-terminate the destination in case the source is longer than the passed size. --- XUtils.c | 12 ++++++++++++ XUtils.h | 3 +++ 2 files changed, 15 insertions(+) diff --git a/XUtils.c b/XUtils.c index 01f33424..fe2d8b9a 100644 --- a/XUtils.c +++ b/XUtils.c @@ -193,6 +193,18 @@ char* String_readLine(FILE* fd) { } } +size_t String_safeStrncpy(char *restrict dest, const char *restrict src, size_t size) { + assert(size > 0); + + size_t i = 0; + for (; i < size - 1 && src[i]; i++) + dest[i] = src[i]; + + dest[i] = '\0'; + + return i; +} + int xAsprintf(char** strp, const char* fmt, ...) { va_list vl; va_start(vl, fmt); diff --git a/XUtils.h b/XUtils.h index 9e5e62cf..6066aa95 100644 --- a/XUtils.h +++ b/XUtils.h @@ -59,6 +59,9 @@ char* String_getToken(const char* line, unsigned short int numMatch); char* String_readLine(FILE* fd); +/* Always null-terminates dest. Caller must pass a strictly positive size. */ +size_t String_safeStrncpy(char *restrict dest, const char *restrict src, size_t size); + ATTR_FORMAT(printf, 2, 3) int xAsprintf(char** strp, const char* fmt, ...);