From 69f9ccf140009197cd673538707b940cdf70bd29 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= Date: Thu, 30 Nov 2017 20:54:31 +0100 Subject: [PATCH] util-lib: handle empty string in last_path_component Now the function returns an empty string when given an empty string. Not sure if this is the best option (maybe this should be an error?), but at least the behaviour is well defined. --- src/basic/path-util.c | 3 +++ src/test/test-path-util.c | 1 + 2 files changed, 4 insertions(+) diff --git a/src/basic/path-util.c b/src/basic/path-util.c index 059e4fcf6a5..3bde1d1e01b 100644 --- a/src/basic/path-util.c +++ b/src/basic/path-util.c @@ -719,6 +719,9 @@ const char *last_path_component(const char *path) { unsigned l, k; l = k = strlen(path); + if (l == 0) /* special case — an empty string */ + return path; + while (k > 0 && path[k-1] == '/') k--; diff --git a/src/test/test-path-util.c b/src/test/test-path-util.c index 21d52f5d6e6..0db835608ad 100644 --- a/src/test/test-path-util.c +++ b/src/test/test-path-util.c @@ -411,6 +411,7 @@ static void test_last_path_component(void) { assert_se(streq(last_path_component("././/"), ".//")); assert_se(streq(last_path_component("/foo/a"), "a")); assert_se(streq(last_path_component("/foo/a/"), "a/")); + assert_se(streq(last_path_component(""), "")); } static void test_filename_is_valid(void) { -- 2.39.2