diff --git a/src/emu/path.c b/src/emu/path.c index 04719aa..2743f18 100644 --- a/src/emu/path.c +++ b/src/emu/path.c @@ -96,7 +96,7 @@ void path_remove_trailing(char *path) { int n = strlen(path); - for (int i = n - 1; path[i] == '/'; i--) { + for (int i = n - 1; i >= 0 && path[i] == '/'; i--) { path[i] = '\0'; } } diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index bab3f52..e40938e 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -14,3 +14,4 @@ unit_test(stream.c) unit_test(thread.c) unit_test(value.c) unit_test(version.c) +unit_test(path.c) diff --git a/test/unit/path.c b/test/unit/path.c new file mode 100644 index 0000000..c7c022b --- /dev/null +++ b/test/unit/path.c @@ -0,0 +1,35 @@ +/* Copyright (c) 2023 Barcelona Supercomputing Center (BSC) + * SPDX-License-Identifier: GPL-3.0-or-later */ + +#include "emu/path.h" +#include "common.h" +#include + +static void +test_underflow_trailing(void) +{ + char in[] = { 'A', '/', '/', '/', '/', '\0', 'B' }; + char out[] = { 'A', '/', '\0','\0','\0','\0', 'B' }; + char *p = in + 2; /* ^here */ + + path_remove_trailing(p); + + if (memcmp(in, out, sizeof(in)) != 0) { + for (size_t i = 0; i < sizeof(in); i++) { + err("i=%3d, in[i]=%02x out[i]=%02x\n", i, + (unsigned char) in[i], + (unsigned char) out[i]); + } + die("path mismatch"); + } + + err("OK\n"); +} + +int +main(void) +{ + test_underflow_trailing(); + + return 0; +}