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, ...);