From c7a457d5bd934a52594c5c87543d7016082c8cb1 Mon Sep 17 00:00:00 2001 From: Joao Matos Date: Wed, 2 Oct 2024 16:28:16 +0100 Subject: [PATCH] Fixed truncation warning in `path_join`. ../../src/host/path_join.c:164:9: warning: 'strncpy' output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation] --- src/host/path_join.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/host/path_join.c b/src/host/path_join.c index c41f1e0b8b..fa8d08400d 100644 --- a/src/host/path_join.c +++ b/src/host/path_join.c @@ -5,6 +5,7 @@ */ #include "premake.h" +#include #include #include "path_isabsolute.h" @@ -150,6 +151,17 @@ int path_has_deferred_join(lua_State* L) return 1; } +// Copy string "in" with at most "insz" chars to buffer "out", which +// is "outsz" bytes long. The output is always 0-terminated. Unlike +// strncpy(), strncpy_t() does not zero fill remaining space in the +// output buffer: +// Credit: https://stackoverflow.com/a/58237928 +static char* strncpy_t(char* out, size_t outsz, const char* in, size_t insz){ + assert(outsz > 0); + while(--outsz > 0 && insz > 0 && *in) { *out++ = *in++; insz--; } + *out = 0; + return out; +} int path_resolve_deferred_join(lua_State* L) { @@ -161,8 +173,7 @@ int path_resolve_deferred_join(lua_State* L) size_t len = strlen(path); int i; int numParts = 0; - strncpy(inBuffer, path, len); - inBuffer[len] = '\0'; + strncpy_t(inBuffer, sizeof(inBuffer), path, len); char *parts[0x200]; // break up the string into parts and index the start of each part nextPart = strchr(inBuffer, DEFERRED_JOIN_DELIMITER);