From be77dd73c769b3e7ac62bd4c0b98242b62d080e0 Mon Sep 17 00:00:00 2001 From: Tom Tromey Date: Fri, 4 Jun 2021 16:00:33 -0600 Subject: [PATCH] Introduce make_unique_xstrndup This adds a new make_unique_xstrndup function, which is the "n" analogue of make_unique_xstrdup. It also updates a couple existing places to use this function. --- gdb/cli/cli-setshow.c | 7 +++---- gdb/parse.c | 3 ++- gdbsupport/gdb_unique_ptr.h | 9 +++++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/gdb/cli/cli-setshow.c b/gdb/cli/cli-setshow.c index dcb50caf5e3..18e2d4ed5c8 100644 --- a/gdb/cli/cli-setshow.c +++ b/gdb/cli/cli-setshow.c @@ -375,14 +375,13 @@ do_set_command (const char *arg, int from_tty, struct cmd_list_element *c) { /* Clear trailing whitespace of filename. */ const char *ptr = arg + strlen (arg) - 1; - char *copy; while (ptr >= arg && (*ptr == ' ' || *ptr == '\t')) ptr--; - copy = xstrndup (arg, ptr + 1 - arg); + gdb::unique_xmalloc_ptr copy + = make_unique_xstrndup (arg, ptr + 1 - arg); - val = tilde_expand (copy); - xfree (copy); + val = tilde_expand (copy.get ()); } else val = xstrdup (""); diff --git a/gdb/parse.c b/gdb/parse.c index b2f23eb67bb..a76a6c1afdb 100644 --- a/gdb/parse.c +++ b/gdb/parse.c @@ -199,7 +199,8 @@ parser_state::mark_completion_tag (enum type_code tag, const char *ptr, || tag == TYPE_CODE_STRUCT || tag == TYPE_CODE_ENUM); m_completion_state.expout_tag_completion_type = tag; - m_completion_state.expout_completion_name.reset (xstrndup (ptr, length)); + m_completion_state.expout_completion_name + = make_unique_xstrndup (ptr, length); } /* See parser-defs.h. */ diff --git a/gdbsupport/gdb_unique_ptr.h b/gdbsupport/gdb_unique_ptr.h index df88cea9cf0..77aecb48e62 100644 --- a/gdbsupport/gdb_unique_ptr.h +++ b/gdbsupport/gdb_unique_ptr.h @@ -64,4 +64,13 @@ make_unique_xstrdup (const char *str) return gdb::unique_xmalloc_ptr (xstrdup (str)); } +/* Dup the first N characters of STR and return a unique_xmalloc_ptr + for the result. The result is always \0-terminated. */ + +static inline gdb::unique_xmalloc_ptr +make_unique_xstrndup (const char *str, size_t n) +{ + return gdb::unique_xmalloc_ptr (xstrndup (str, n)); +} + #endif /* COMMON_GDB_UNIQUE_PTR_H */ -- 2.30.2