Avoid cloning static strings for "struct datatype". With concat_type_alloc(), the name/desc are generated dynamically and need to be allocated. However, datatype_clone() only reuses the original name/desc strings. If those strings are static already, we don't need to clone them. Note that there are no other places that also want to change or set the name/desc. If there were, they would need to handle the new fact that the strings may or may not be dynamically allocated. Signed-off-by: Thomas Haller <thaller@xxxxxxxxxx> --- include/datatype.h | 2 ++ src/datatype.c | 15 ++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/include/datatype.h b/include/datatype.h index b53a739e1e6c..465ade290652 100644 --- a/include/datatype.h +++ b/include/datatype.h @@ -132,6 +132,7 @@ struct parse_ctx; * @f_prefix: preferred representation for ranges is a prefix * @f_alloc: whether the instance is dynamically allocated. If not, datatype_get() and * datatype_free() are NOPs. + * @f_allocated_strings: whether @name and @desc are heap allocated or static. * @name: type name * @desc: type description * @basetype: basetype for subtypes, determines type compatibility @@ -153,6 +154,7 @@ struct datatype { enum byteorder byteorder; bool f_prefix:1; bool f_alloc:1; + bool f_allocated_strings:1; const char *name; const char *desc; diff --git a/src/datatype.c b/src/datatype.c index 464eb49171c6..1c557a06c751 100644 --- a/src/datatype.c +++ b/src/datatype.c @@ -1244,8 +1244,10 @@ struct datatype *datatype_clone(const struct datatype *orig_dtype) dtype = xzalloc(sizeof(*dtype)); *dtype = *orig_dtype; - dtype->name = xstrdup(orig_dtype->name); - dtype->desc = xstrdup(orig_dtype->desc); + if (orig_dtype->f_allocated_strings) { + dtype->name = xstrdup(orig_dtype->name); + dtype->desc = xstrdup(orig_dtype->desc); + } dtype->f_alloc = true; dtype->refcnt = 1; @@ -1265,8 +1267,10 @@ void datatype_free(const struct datatype *ptr) if (--dtype->refcnt > 0) return; - xfree(dtype->name); - xfree(dtype->desc); + if (dtype->f_allocated_strings) { + xfree(dtype->name); + xfree(dtype->desc); + } xfree(dtype); } @@ -1299,7 +1303,8 @@ const struct datatype *concat_type_alloc(uint32_t type) dtype = datatype_alloc(); dtype->type = type; dtype->size = size; - dtype->subtypes = subtypes; + dtype->subtypes = subtypes; + dtype->f_allocated_strings = true; dtype->name = xstrdup(name); dtype->desc = xstrdup(desc); dtype->parse = concat_type_parse; -- 2.41.0